一个<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 剪贴板插件?
最佳答案
我曾经使用伪造的文本区域元素将我的自定义文本复制到剪贴板来解决这个问题。
这样的事情应该有所帮助:
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);
}
关于javascript - 如何使用旧版免费 JavaScript 将标记(不仅仅是纯文本)复制到剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46522213/