如何使ClipboardJS复制文本及其超链接?

时间:2019-08-19 04:32:33

标签: jquery html clipboard.js

如何使ClipboardJS可以复制文本及其超链接?我已经尝试使用data-link,但是没有运气,

clipboard.on('success', function(e) {
    var aff_link = $(this).attr('data-link'); 
});

这是我已经尝试制作的,而html是<span id="clipboard" data-clipboard-text="this is a text" data-link="#">copy</span>

2 个答案:

答案 0 :(得分:0)

您可以使用hidden input value进行尝试。

var clipboard = new Clipboard('.btn-copy', {
  text: function() {
    return document.querySelector('input[type=hidden]').value;
  }
});
clipboard.on('success', function(e) {
  alert("Copied!");
  e.clearSelection();
});
$("#input-url").val(location.href);
.wrapper {
  width: 100%;
  height: 100%;
  text-align: center;
  margin-top: 10px;
}

.btn-copy {
  background-color: #38AFDD;
  border: transparent;
  border-bottom: 2px solid #0086B7;
  border-radius: 2px;
  padding: 10px;
  min-width: 100px;
  color: #fff;
}

.btn-copy:hover,
.btn-copy:focus {
  background-color: #48A1C1;
  border-bottom: 2px solid #38AFDD;
  /*transition cross browser*/
  transition: all .3s ease-in;
  -webkit-transition: all .3s ease-in;
  -moz-transition: all .3s ease-in;
  -o-transition: all .3s ease-in;
}
<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.10/clipboard.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
  <h3>Click button below to copy current url to clipboard with hidden input</h3>
  <input type="hidden" id="input-url" value="www.google.com">
  <button class="btn-copy">Copy</button>
</div>

答案 1 :(得分:0)

Easy Code ;)

<!-- The text field -->
    <input type="text" value="Hello World" id="myInput">

    <!-- The button used to copy the text -->
    <button onclick="myFunction()">Copy text</button>


    function myFunction() {
      /* Get the text field */
      var copyText = document.getElementById("myInput");

      /* Select the text field */
      copyText.select();

      /* Copy the text inside the text field */
      document.execCommand("copy");

      /* Alert the copied text */
      alert("Copied the text: " + copyText.value);
    }