实现的效果如下图所示:(注:图是第三种方法)
复制完成后就直接ctrl+v粘贴就行了:
1. 第一种方法 ,运用隐藏textarea来实现复制
<div style="padding-bottom:10px" id="copyId">
水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水
水水水水水水水水水水水水水水水水水水水水水水水水水
</div>
<textarea id="input" ></textarea>
<button type="button" (click)="copy()"></button>
ts中的执行方法是:
copy(){
var text = document.getElementById("copyId").innerText;
var input = document.getElementById("input");
input.textContent = text; // 修改文本框的内容
input.select(); // 选中文本
document.execCommand("copy"); // 执行浏览器复制命令
}
css的设置为:
#input {position: absolute;top: 0;left: 0;opacity: 0;z-index: -10;}
2. 第二种办法:虚拟一个新建一个div
var oInput = document.createElement('input');
oInput.value = "sssssssssssss";
document.body.appendChild(oInput);
oInput.select(); // 选择对象
document.execCommand("Copy"); // 执行浏览器复制命令
oInput.className = 'oInput';
oInput.style.display = 'none';
3. 第三种方法,windows选中的方法
<div style="padding-bottom:10px" id="copyId">
水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水
水水水水水水水水水水水水水水水水水水水水水水水水水
</div>
<button type="button" (click)="copy()"></button>
ts的执行方法是:
copy() {
var val = document.getElementById('copyId');
window.getSelection().selectAllChildren(val);
document.execCommand("Copy");
}
本文参考文献:1. 原生 js 实现点击按钮复制文本 - Wise.Wrong - 博客园