将元素的文本 innerHTML 复制到剪贴板

新手上路,请多包涵

我在 stackoverflow 中尝试了很多解决方案,但没有用。( 这里这里

我在 网站 上尝试并使用 chrome 扩展 程序运行代码(chrome 59.0.3071.104 64 位)

 <h4 align="center">text data to copy</h4>

var copy_text = document.getElementsByTagName("h4")[0];
copy_text.select(); //-> error: select is not a function

var range = document.createRange();
range.selectNode(copy_text);
window.getSelection().addRange(range);
document.execCommand("copy"); //-> clipboard not change

有什么解决办法吗?谢谢你。


编辑:我认为我的问题是页面加载(安全浏览器),所有解决方案都与用户交互

原文由 Trương Quốc Khánh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 435
1 个回答

在这里,第一个例子。 https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f 。我的例子是根据我的需要重写的,但你会明白的:)

 <div onclick="bufferText()">Миньор Перник!</div>
<script>
   function bufferText() {
        const el = document.createElement("textarea");
        el.value = event.target.innerHTML;
        document.body.appendChild(el);
        el.select();
        document.execCommand("copy");
        document.body.removeChild(el);
   }
</script>

原文由 MetaTron 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题