js 實現點擊按鈕複製文本

原理:

瀏覽器提供了 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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章