复制文本
本案例来自三方开发者「Peng」
1. 使用场景
本例介绍如何在宜搭中实现文本复制。
2. 实现功能
2.1. 创建自定义页面

2.2. 文本复制函数
/**
* 文本复制
* @param text 需要复制的内容
*/
export function copyToClip(text) {
if (this.utils.isMobile() && window.dd) {
dd.biz.clipboardData.setData({
text,
onSuccess: () => {
this.utils.toast({
title: '复制成功',
type: 'success',
});
},
onFail: () => {
this.utils.toast({
title: '复制失败',
type: 'error',
});
},
})
} else {
if (navigator.clipboard && window.isSecureContext && typeof navigator.clipboard.writeText === 'function') {
navigator.clipboard.writeText(text).then(() => {
this.utils.toast({
title: '复制成功',
type: 'success',
});
}).catch(() => {
this.utils.toast({
title: '复制失败',
type: 'error',
});
});
} else {
try {
const input = document.createElement('input');
input.readOnly = 'readonly';
input.value = text;
document.body.appendChild(input);
input.select();
input.setSelectionRange(0, input.value.length);
document.execCommand('Copy');
document.body.removeChild(input);
this.utils.toast({
title: '复制成功',
type: 'success',
});
} catch (err) {
this.utils.toast({
title: '复制失败',
type: 'error',
});
}
}
}
}
2.3. 函数使用

调用示例:
// 点击复制
export function onClick() {
this.copyToClip(this.$('textareaField_l9pdlt0k').getValue());
}
3. 实现效果


4. 在线试玩
本文档对您是否有帮助?