简体   繁体   English

使用Clipboard.js复制跨度文本

[英]Copy span text using Clipboard.js

I'm using clipboard.js and need to copy the text in a span by clicking a button. 我正在使用clipboard.js,需要通过单击按钮来复制跨度中的文本。 Is there a way to do this? 有没有办法做到这一点?

HTML: HTML:

<span id="spanId">text here</span>
<input type="button" class="buttonClass" value="Copy" data-clipboard-target="#spanId" />

A solution can be: 解决方案可以是:

 // create a new instance of Clipboard plugin for the button element // using the class selector: .buttonClass var clipboard = new Clipboard('.buttonClass'); // when text is copied into clipboard use it clipboard.on('success', function(e) { $('#log').text('Text copied into clipboard is: <' + e.text + '>'); e.clearSelection(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.10/clipboard.min.js"></script> <span id="spanId">text here</span> <input type="button" class="buttonClass" value="Copy" data-clipboard-target="#spanId"/> <p id="log"></p> 

I'm still learning JS my self however, i found this on the clipboard.js github here . 我还在学习JS我的自己,我在剪贴板上找到了这个.js github 在这里 i would of made this a comment but dont have the rep. 我想这是一个评论,但没有代表。

<!-- Target -->
<span id="spanId">text here</span>
<!-- Trigger -->
<button class="btn" data-clipboard-target="#spanId">
<img src="assets/clippy.svg" alt="Copy to clipboard">
</button>

ive also never seen input type button before so looked on the mozilla developer network here and it says that "...It has been superseded in HTML5 by the element.". 我也没见过输入类型按钮,所以在这里查看 mozilla开发者网络,它说“......它已经被HTML5取代了。”。 So i would maybe look into that as it seems to be a better way of doing it. 所以我可能会考虑这一点,因为它似乎是一种更好的方式。

You'll just need to instantiate a new Clipboard. 您只需要实例化一个新的剪贴板。 In this case you'd write new Clipboard(".buttonClass") because that's the class your button has. 在这种情况下,您将编写new Clipboard(".buttonClass")因为这是您的按钮所具有的类。 The markup you've provided was completely functional otherwise. 您提供的标记完全无效。 I've made a JSFiddle that you can view here . 我已经制作了一个JSFiddle,你可以在这里查看。

If you're having any other trouble, I found the clipboard.js docs to be very helpful. 如果您遇到任何其他问题,我发现clipboard.js文档非常有用。

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

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