我有一个带有 id
copy
的 div
和一个按钮。我想在单击该按钮时复制 div
内容放入剪贴板
function myFunction() {
var copyText = document.getElementById("copy");
copyText.innerHTML=html;
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
这是我到目前为止所尝试过的,但似乎不起作用。 请帮我。 我该怎么办?
最佳答案
我使用了这个方法并且有效:
function CopyToClipboard(id){
var r = document.createRange();
r.selectNode(document.getElementById(id));
window.getSelection().removeAllRanges();
window.getSelection().addRange(r);
try {
document.execCommand('copy');
window.getSelection().removeAllRanges();
console.log('Successfully copy text: hello world ' + r);
} catch (err) {
console.log('Unable to copy!');
}
}
<div id="div_id">Hello World From div Content</div>
<button type="button" onclick="CopyToClipboard('div_id')">Copy text</button>
我从 here 得到了这个代码.
关于javascript - 如何将div内容复制到剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60745869/