html:
<span class='copyPhone'>1008611</span><span onclick="copyPhone()">复制</span>
js:
function copyPhone(){
let copyPhone = document.getElementsByClassName('copyPhone')[0].innerText;
let copy = function (e){
e.preventDefault();
e.clipboardData.setData('text/plain',copyPhone);
console.log('复制成功')
document.removeEventListener('copy',copy);
}
document.addEventListener('copy',copy);
document.execCommand("copy");
}
步骤:1。document.addEventListener('copy',copy); 监听copy事件,
2。document.execCommand("copy"),触发copy监听事件
3。e.clipboardData.setData('text/plain',copyPhone); 将内容copyPhone 添加到剪切板
4。document.removeEventListener取消监听