简体   繁体   English

如何复制部分 <p> 文字点击

[英]How do I copy portion of <p> text onClick

I have an HTML document with a 'p' element which I would like a portion of copied to the clipboard when the whole element is clicked. 我有一个带有'p'元素的HTML文档,当单击整个元素时,我希望将其复制到剪贴板中。

<p class="pageID"><strong>Page ID: </strong>#A16</p>

Which returns: PageID: #A16 返回值: PageID: #A16

I want to have it so when I click anywhere on this line the page ID (#A16) is copied to the clipboard but nothing else. 我想要它,所以当我单击此行上的任何位置时,页面ID(#A16)都将复制到剪贴板,但没有其他内容。 I've seen some similar questions on here and tried a bunch of different JavaScript solutions but nothing is working. 我在这里看到过类似的问题,并尝试了许多不同的JavaScript解决方案,但没有任何效果。

Any ideas? 有任何想法吗?

Thanks! 谢谢!

You could try something like this: 您可以尝试这样的事情:

<p class="pageID"><strong>Page ID: </strong><span id="toCopy">#A16</span></p>

<script>
document.querySelector(".pageID").addEventListener('click', function() {
   var temp_input = document.createElement("INPUT");
   temp_input.value = document.querySelector('#toCopy').innerHTML;
   temp_input.select();
   document.execCommand("copy");
});
</script>

No jQuery needed! 无需jQuery!

Off the top of the head, I'd wrap whatever you're trying to copy into it's own element and copy the text of the element. 在头顶上方,我会将要复制的内容包装到它自己的元素中,然后复制该元素的文本。

ex: <p class="pageID"><strong>Page ID: </strong><span class="your-class-name">#A16</span></p> 例如: <p class="pageID"><strong>Page ID: </strong><span class="your-class-name">#A16</span></p>

You should wrap that text in element with some id and then focus on it and copy like this 您应该将该文本包装在具有一些id的元素中,然后专注于它并像这样复制

var el = document.getElementById("myText");
el.select();
document.execCommand("copy");

You can do something like this: 您可以执行以下操作:

<div id="myId"><p class="pageID" id="myElement"><strong>Page ID: </strong>#A16</p></div>

<script>
$('#myId').onClick(function() {
  var copyText = document.getElementById("myElement");
  copyText.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value); // do whatever you want with this text.
});
</script>

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

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