
实现一个具有复制功能的文字按钮
通过点击按钮实现指定文字的复制功能。
文章目录
1.效果图


2.关键代码
html
#template
<span id="copycontent">{{web_url}}</span><button style="position: relative; top: -2px;left: 5px;" variant="text" theme="success" @click="copyClick">复制</button>
javascript
#script
methods: {
copyClick(){
var input = document.createElement('input');
document.body.appendChild(input);
var content = document.querySelector('#copycontent').innerHTML;
input.setAttribute('value', content);
input.select();
if (document.execCommand('copy')) {
document.execCommand('copy');
this.$message.success(this.$t('copy_succ'));
}
document.body.removeChild(input);
},
}
总结
通过操作DOM 使用 document.execCommand('copy') 是用于复制选中文本到剪贴板的命令。但是document.execCommand 存在兼容性问题,部分浏览器可能已经不再支持。