<div>
<div id="myElement">
Mary had a little <b>lamb</b>, its <i>fleece</i> was white as snow. Everywhere that mary went, the lamb was sure to go.
</div>
应使用此代码将复制到剪贴板
const copyAll = document.querySelector("myElement");
window.getSelection().selectAllChildren(copyAll);
document.execCommand("Copy");
window.getSelection().removeAllRanges();
(要使execCommand正常工作,必须通过事件监听器执行调用)
但只复制了文本内容。是否可以复制标记代码(<i>
和<b>
标记)而不依赖于依赖于旧版的firefox剪贴板附加组件?
答案 0 :(得分:2)
我曾经使用假的textarea元素将我的自定义文本复制到剪贴板来解决这个问题。
这样的事情应该会有所帮助:
const copyText = document.querySelector("myElement").innerHTML;
copyToClipboard(copyText);
function copyToClipboard(message) {
let textArea = document.createElement("textarea");
textArea.value = message;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("copy");
document.body.removeChild(textArea);
}