如何在没有Flash的情况下复制一个div的内容到剪贴板

13

好的 :) 我有一个id为#toCopy的div,以及一个id为#copy的按钮。 当按下#copy按钮时,复制#toCopy内容到剪贴板的最佳方法是什么?


1
你有检查右侧“相关”标题下显示的任何“如何将内容复制到剪贴板”的问题吗? - Pointy
2
如何在 JavaScript 中复制到剪贴板? - Emil L
1
唯一支持在没有Flash或其他第三方解决方案的情况下复制到剪贴板的浏览器是Internet Explorer,所以祝你好运。 - adeneo
2
终于在IE中有了好处 @adeneo - Idris
3个回答

54

在几乎任何浏览器上,你都可以从只有 input 元素(即具有 .value 属性的元素)中复制到剪贴板,但是无法从像 <div><p><span> 这样的元素(即具有 .innerHTML 属性的元素)中复制。

不过我使用以下技巧实现了这一点:

  1. 创建一个临时的输入元素,比如说 <textarea>
  2. <div>innerHTML 复制到新创建的 <textarea>
  3. <textarea>.value 复制到剪贴板
  4. 移除我们刚刚创建的临时 <textarea> 元素

function CopyToClipboard (containerid) {
  // Create a new textarea element and give it id='temp_element'
  const textarea = document.createElement('textarea')
  textarea.id = 'temp_element'
  // Optional step to make less noise on the page, if any!
  textarea.style.height = 0
  // Now append it to your page somewhere, I chose <body>
  document.body.appendChild(textarea)
  // Give our textarea a value of whatever inside the div of id=containerid
  textarea.value = document.getElementById(containerid).innerText
  // Now copy whatever inside the textarea to clipboard
  const selector = document.querySelector('#temp_element')
  selector.select()
  document.execCommand('copy')
  // Remove the textarea
  document.body.removeChild(textarea)
}
<div id="to-copy">
  This text will be copied to your clipboard when you click the button!
</div>
<button onClick="CopyToClipboard('to-copy')">Copy</button>


2
非常好! - Eric
2
比我见过的任何“输入”实现都要好,并且可以与多个复制元素一起使用。谢谢! - nml
1
为什么函数的每行末尾都没有使用分号呢? - Jalali Shakib
1
@JalaliShakib 在 JavaScript 中是可选的。 - Hani
1
这在火狐浏览器中不起作用。火狐浏览器版本为43.0.1。 - Karuppiah RK
2
有趣的是指出具有.value属性的元素的差异。是的,它运行得非常好。 - Andrea Antonangeli

0

没有id的相同:

function copyClipboard(el, win){
   var textarea,
       parent;

   if(!win || (win !== win.self) || (win !== win.window))
      win = window;
   textarea = document.createElement('textarea');
   textarea.style.height = 0;
   if(el.parentElement)
      parent = el.parentElement;
   else
      parent = win.document;
   parent.appendChild(textarea);
   textarea.value = el.innerText;
   textarea.select();
   win.document.execCommand('copy');
   parent.removeChild(textarea);
}

不过我没有测试过不同的窗口(iframes)!


-5

这是一个相对较新的功能,因为在我回答这个问题时它还没有得到支持。使用此功能需要小心,因为只有最新的浏览器支持它,而这对于某些目标受众来说可能不太好。最好的方法是使用Flash,或者创建一个支持Flash作为后备方案的polyfill。如果您不能使用Flash,则根本不要实现此功能,或者提供仅在支持该功能的浏览器上使用它的可能性,并确保不支持它的浏览器也可以正常工作。 - Zezura
你不能将最新版本的浏览器视为支持它,因为并不是每个人都拥有最新版的浏览器,即使在默认启用自动更新的 Chrome 中也是如此。 - Zezura
根据mozilla的文档,Safari不支持该功能,因此最好的编程范例是创建一个回退(polyfill),在其中您可以显示一个带有问题的消息,询问他们是否按下CTRL + C,而不是一个无法工作的按钮。你最好是安全的,而不是抱有侥幸心理。不要懒惰。这是今天和未来的最佳方式。另外,https://clipboardjs.com/也是一种不错的方式,如果Safari更新了,您只需要更新lib.js即可。 - Zezura
这就是我所说的。Safari出于安全考虑没有实现这个功能。它目前只占有大约3%的浏览器使用率,这不应该成为使用不安全的Flash备用方案的理由。 - Błażej Michalik
我同意,只要确保在不支持时不显示复制粘贴按钮,对吧 :) - Zezura
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接