原理:
瀏覽器提供了 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;
}