使用Clipboard.js复制跨度文本

时间:2016-05-19 17:48:01

标签: javascript html clipboard clipboard.js

我正在使用clipboard.js,需要通过单击按钮来复制跨度中的文本。有没有办法做到这一点?

HTML:

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

3 个答案:

答案 0 :(得分:3)

解决方案可以是:

// 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>

答案 1 :(得分:2)

我仍然在学习JS我的自己,但我在clipboard.js github here上找到了这个。我想把它作为评论,但没有代表。

<!-- 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>

我从未见过输入类型按钮,因此在浏览mozilla开发者网络here时它会说“......它已被HTML5取代了。”。所以我可能会考虑这一点,因为它似乎是一种更好的方式。

答案 2 :(得分:2)

您只需要实例化一个新的剪贴板。在这种情况下,您要写new Clipboard(".buttonClass"),因为这是您的按钮所具有的类。您提供的标记完全无效。我已经创建了一个JSFiddle,您可以查看here

如果您遇到任何其他问题,我发现clipboard.js docs非常有帮助。