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

标签 javascript

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

我在 Website 中尝试并使用 chrome extension用于运行代码(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

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


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

最佳答案

这里是第一个例子。 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>

关于javascript - 将元素的文本 innerHTML 复制到剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44908329/

相关文章:

正则表达式 : how to remove string before > and including >

javascript - 当 div 状态改变时改变输入

javascript - 无法加载 jQuery,因为它违反了内容安全策略

javascript - React-navigation重置说明

javascript - 强制重新评估内联并包含 Javascript

c# - javascript 对象中的成员可见性和 'this' 范围

javascript - 我们可以查看 emberjs 中的所有路由,也就是类似于 rake 路由在 rails 中所做的事情吗

javascript if 语句不起作用

Javascript:如何编写将异步执行的函数?

javascript - 在回调中调用方法