问题
The complete content of a <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>
should be copied to the clipboard using this code
const copyAll = document.querySelector("myElement");
window.getSelection().selectAllChildren(copyAll);
document.execCommand("Copy");
window.getSelection().removeAllRanges();
(For the execCommand to work, the call must be executed via an event listener)
But only the text-content is copied. Is it possible to copy the markup-code (the <i>
and <b>
tags) without relying on the legacy firefox clipboard add-on, too?
回答1:
I used to solve this problem using a fake textarea element copying my custom text into the clipboard.
Something like this should help:
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);
}
来源:https://stackoverflow.com/questions/46522213/how-to-copy-markup-not-just-plain-text-to-the-clipboard-using-legacy-free-ja