如何将文本从div复制到剪贴板

以下是用户点击此按钮时的代码:

 

如何复制此div中的文本?

 
Text To Copy

两者都会像魅力:),

  1. JAVASCRIPT:

     function CopyToClipboard(containerid) { if (document.selection) { var range = document.body.createTextRange(); range.moveToElementText(document.getElementById(containerid)); range.select().createTextRange(); document.execCommand("copy"); } else if (window.getSelection) { var range = document.createRange(); range.selectNode(document.getElementById(containerid)); window.getSelection().addRange(range); document.execCommand("copy"); alert("text copied") }} 

也在html中,

  
Text To Copy

我尝试了上面提出的解决方案。 但它不够跨浏览器。 我真的需要ie11才能工作。 尝试后我得到:

   
Click to copy

使用firefox 57,Chrome 63,Opera 49,ie11测试,只有边缘不起作用。

如果要复制多个项目,并且每个项目都有一个单独的“复制到剪贴板”按钮,则接受的答案不起作用。 单击一个按钮后,其他按钮将无法工作。

为了使它们起作用,我在接受答案的函数中添加了一些代码,以便在执行新文本选择之前清除文本选择:

 function CopyToClipboard(containerid) { if (window.getSelection) { if (window.getSelection().empty) { // Chrome window.getSelection().empty(); } else if (window.getSelection().removeAllRanges) { // Firefox window.getSelection().removeAllRanges(); } } else if (document.selection) { // IE? document.selection.empty(); } if (document.selection) { var range = document.body.createTextRange(); range.moveToElementText(document.getElementById(containerid)); range.select().createTextRange(); document.execCommand("copy"); } else if (window.getSelection) { alert(containerid); var range = document.createRange(); range.selectNode(document.getElementById(containerid)); window.getSelection().addRange(range); document.execCommand("copy"); alert("text copied") } } 

添加链接作为答案,以便在第一个答案下面更多地关注Aaron Lavers的评论。

这就像一个魅力 – http://clipboardjs.com 。 只需添加clipboard.js或min文件即可。 在启动时,使用具有要点击的html组件的类,并将具有要复制的内容的组件的id传递给click元素。