如何使用旧版免费JavaScript将标记(不仅仅是纯文本)复制到剪贴板 [英] How to copy markup - not just plain text - to the clipboard using legacy free JavaScript

查看:47
本文介绍了如何使用旧版免费JavaScript将标记(不仅仅是纯文本)复制到剪贴板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

< 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();

(要使execCommand正常工作,必须通过事件侦听器执行调用)

但仅复制文本内容.是否可以不依赖传统的Firefox剪贴板而复制标记代码(< i> &b; b> 标签)也是吗?

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?

推荐答案

我曾经使用伪造的textarea元素将我的自定义文本复制到剪贴板中来解决此问题.

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);
    }

这篇关于如何使用旧版免费JavaScript将标记(不仅仅是纯文本)复制到剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆