3个思路
execCommand
(已弃用)Clipboard API
clipboard.js
execCommand实现
这个API已经被弃用了
var textarea=document.createElement('textarea');
textarea.value=document.getElementById('target').textContent;
textarea.style.cssText = 'position:absolute;top:-999999px;'; // 让textare元素看不见,但是需要能正常获取其value
document.body.appendChild(textarea);
if(document.execCommand('copy')){ // 如果支持拷贝命令
textarea.select();
document.execCommand('copy');
}
document.removeChild(textarea)
Clipboard API
火狐等浏览器复制是需要用户触发才行的
<body>
<input id="text" value=""></input>
<button onclick="click1()">复制</button>
<div>
复制的内容:
<div id="textContent"></div>
</div>
</body>
<script>
function click1() {
navigator.clipboard.writeText(document.getElementById('text').value);
navigator.clipboard.readText().then(
clipText => document.getElementById("textContent").innerText = clipText
);
}
</script>
兼容性:
clipboard.js
直接贴链接了 clipboard.js