jquery 如何不使用flash将div的内容复制到剪贴板

kgsdhlau  于 2022-12-26  发布在  jQuery
关注(0)|答案(3)|浏览(94)

就是这样:)我有一个id为**#toCopy的div,还有一个id为#copy的按钮,当按下#copy时,将#toCopy**内容复制到剪贴板的最佳方法是什么?

lqfhib0f

lqfhib0f1#

您几乎可以在任何浏览器中从input元素(具有.value属性的元素)复制到剪贴板,但不能从<div><p><span> ...(具有.innerHTML属性的元素)复制到剪贴板。
但我用这个技巧来做到这一点:
1.创建一个临时输入元素,例如<textarea>
1.将innerHTML<div>复制到新创建的<textarea>
1.将<textarea>.value复制到剪贴板
1.删除我们刚刚创建的临时<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>
yc0p9oo0

yc0p9oo02#

没有身份证也一样:

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)虽然!

ovfsdjhp

ovfsdjhp3#

    • 更新的答案**Javascript早期被限制使用剪贴板。但是现在它支持复制/粘贴命令。参见mozilla和caniuse.com的文档。
document.execCommand('paste')

请确保您支持不支持的浏览器。
https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand http://caniuse.com/#search=command
javascript不允许使用剪贴板,但其他插件如flash可以访问。
How do I copy to the clipboard in JavaScript?

相关问题