如何将div的内容复制到没有flash的剪贴板

Lui*_*ego 9 html javascript jquery copy

这是它:)我有id为一个div #toCopy,并与ID按钮#copy.按#copy时,将#toCopy内容复制到剪贴板的最佳方法是什么?

Han*_*ani 42

您可以复制到剪贴板,几乎在任何浏览器从输入元素只(元素具有.value属性),但你不能从相同的元素<div>,<p>,<span>...(元素具有.innerHTML属性).

但是我用这个技巧来做到这一点:

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

function CopyToClipboard (containerid) {
  // Create a new textarea element and give it id='temp_element'
  var 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
  var selector = document.querySelector('#temp_element')
  selector.select()
  document.execCommand('copy')
  // Remove the textarea
  document.body.removeChild(textarea)
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

不太晚但希望有所帮助!

  • 效果很好! (2认同)
  • 比我见过的任何“输入”之类的实现都要好,并且可以与多个复制元素一起使用。谢谢! (2认同)
  • 指出与具有 .value 属性的元素的差异很有趣。是的,效果很好 (2认同)