简体   繁体   English

从复制文本<p></p>使用按钮和 JS 到剪贴板?

[英]copy text from <p></p> to clipboard with button and JS?

I have in my html this text:我的 html 中有这段文字:

<button>copy text!</button>
<p>blah</p>

I want the text in the p tags to be copied to clipboard when I click the button.我希望在单击按钮时将 p 标签中的文本复制到剪贴板。 Every tutorial online under the sun talks about using textArea tags but I don't want to use those.太阳下的每个在线教程都在谈论使用 textArea 标签,但我不想使用它们。 Why can't it just be copied this way directly from p tags?为什么不能直接从 p 标签这样复制呢?

You can now use the clipboard API to write to clipboard without using the textarea element (please note that it is currently in working draft status, supported in all commonly used browsers, except IE): Clipboard.writeText()您现在可以使用剪贴板 API 写入剪贴板,而无需使用 textarea 元素(请注意,它目前处于工作草稿状态,在除 IE 之外的所有常用浏览器中均受支持): Clipboard.writeText()

<button>copy text!</button>
<p>blah</p>
const button = document.querySelector( 'button' );
const elementToCopy = document.querySelector( 'p' );
const textToCopy = elementToCopy.innerText;

function copy ( text ) {
  navigator.clipboard.writeText( text )
}

button.addEventListener( 'click' , () => {
  copy( textToCopy )
})

You should now be able to have the content of your p copied to clipboard.您现在应该能够将p的内容复制到剪贴板。

It can easily be achieved with ClipboadJs .使用ClipboadJs可以轻松实现。 They have a good documentation you can follow.他们有一个很好的文档,您可以遵循。

Well I found this workaround which seems like a crime against html but it works.好吧,我发现这个解决方法似乎是针对 html 的犯罪,但它确实有效。 Essentially I have to use a textarea after all by creating it with the contents of the <p> tags and then immediately destroy the textarea element after.基本上我必须通过使用 <p> 标签的内容创建它来使用 textarea,然后立即销毁 textarea 元素。 This feels ridiculous.这感觉很荒谬。

function copyElementText(id) {
  var text = document.getElementById(id).textContent
  var elem = document.createElement("textarea");
  x = document.body.appendChild(elem);
  elem.value = text;
  elem.select();
  document.execCommand("copy");
  x.remove()
  alert("Copied the text: " + text);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM