一、具体场景
前端有时需要实现点击按钮复制的功能,这个时候就不能让用户去手动选择内容右键复制了。
二、实现方式
1. document.execCommand
(1)具体实现
复制时,先选中文本,然后调用document.execCommand(‘copy’),选中的文本就会进入剪贴板。这就需要借助输入框来实现对文本的选中。
具体案例:
<button type="button" onclick="theCopy()">复制</button>
<label style="display: block">
<textarea id="textArea">哈哈哈哈哈哈哈哈哈111111</textarea>
</label>
function theCopy() {
let textArea = document.getElementById('textArea')
console.log(textArea);
textArea.select()
document.execCommand('copy')
}
html加js这些就可以实现,但是我又发现另一种写法!!
如果内容不在输入框中,我们可以借助一个透明的输入框来实现
<button type="button" onclick="theCopy()">复制</button>
<p id="text">哈哈哈哈哈哈哈哈哈111111</p>
<label style="display: block">
<textarea id="textArea" style="opacity: 0;"></textarea>
</label>
function theCopy() {
let textArea = document.getElementById('textArea')
let text = document.getElementById('text')
textArea.innerText = text.innerHTML
console.log(textArea);
textArea.select()
document.execCommand('copy')
}