原理:
浏览器提供了 copy 命令 ,可以复制选中的内容
document.execCommand("copy")
可以通过 select() 方法,选中输入框的文本,然后调用 copy 命令,将文本复制到剪切板
select() 方法只对 input 和 textarea 有效
代码部分:
- html:
<input readonly id="copy_select" :value="35085412124542154">
<button @click="copyId()"></button>
- js:
document.getElementById('copy_select').select();
if (document.execCommand('copy')) {
document.execCommand('copy');
this.$Message.success('复制成功');
}else{
this.$Message.error('复制失败');
}
- css:
#copy_select{
background: transparent;
border: none;
outline: none;
}