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

本文介绍了一种使用JavaScript实现的一键复制文本到剪切板的方法。通过结合document.execCommand('copy')命令和select()方法,可以轻松地将输入框内的文本复制到剪切板。文章提供了具体的HTML、CSS和JS代码示例。
490

被折叠的 条评论
为什么被折叠?



