How to copy markup - not just plain text - to the clipboard using legacy free JavaScript

笑着哭i 提交于 2021-01-28 06:12:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!