admin管理员组

文章数量:1401795

I'm using clipboard.js and need to copy the text in a span by clicking a button. Is there a way to do this?

HTML:

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

I'm using clipboard.js and need to copy the text in a span by clicking a button. Is there a way to do this?

HTML:

<span id="spanId">text here</span>
<input type="button" class="buttonClass" value="Copy" data-clipboard-target="#spanId" />
Share Improve this question edited May 19, 2016 at 18:06 Rose asked May 19, 2016 at 17:48 RoseRose 3631 gold badge3 silver badges15 bronze badges 3
  • why yes. yes there is. – I wrestled a bear once. Commented May 19, 2016 at 17:50
  • @Pamblam haha mind elaborating? – Rose Commented May 19, 2016 at 18:01
  • OK with a button, but what about copying the inner text/html of a span tag when the span is selected using the select event? – user2505564 Commented Oct 18, 2019 at 9:22
Add a ment  | 

2 Answers 2

Reset to default 3

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./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare./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>

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. The markup you've provided was pletely functional otherwise. I've made a JSFiddle that you can view here.

If you're having any other trouble, I found the clipboard.js docs to be very helpful.

本文标签: javascriptCopy span text using ClipboardjsStack Overflow