项目中有点击某个按钮即复制某文本的需求,这里总结两种方式。
方法一
原理:创建一个隐藏的input,并赋值需要执行复制的文本,选中input中的内容,执行dom自带的复制方法。
function copyPwd(copyText) {
let input = document.createElement('input') // 创建一个input
input.value = copyText // 赋值需要复制的内容
document.body.appendChild(input) // 插入dom
input.select() // 选择对象
document.execCommand('Copy') // 执行浏览器复制命令
input.style.display = 'none' // 隐藏
document.body.removeChild(input) // 移除创建的input
alert('Copy Successfully!')
}
注意:隐藏input的代码必须写在执行复制代码的后面,否则无法复制所需的内容!
方法二
原理:创建事件监听器,监听‘copy’,以vue项目为例:
created() {
document.addEventListener('copy', (e) => {
this.eventListenerCopy(e);
});
},
destroyed() {
document.removeEventListener('copy', (e) => {
this.eventListenerCopy(e);
});
},
methods: {
eventListenerCopy(e){
e.clipboardData.setData('text/plain', this.copyText);
e.preventDefault();
},
copy() {
document.execCommand('Copy'); // 执行浏览器复制命令
}
}