在Javascript中添加复制按钮

时间:2015-07-22 17:45:46

标签: javascript html zeroclipboard

我尝试添加一个按钮,使用ZeroClipboard从textarea复制文本,但是,当我点击按钮时,没有任何反应,当我粘贴时,没有任何内容添加到剪贴板。

var clip = new ZeroClipboard( document.getElementById("btn4"), {
  moviePath: "https://rawgit.com/zeroclipboard/zeroclipboard/master/dist/ZeroClipboard.swf"
} );

clip.on( "load", function(client) {
  // alert( "movie is loaded" );

  client.on( "complete", function(client, args) {
    // `this` is the element that was clicked
    this.style.display = "none";
  } );
} );
<div id ="right" style = "float:left; width: 10%; margin-left:185px; margin-top:35px">
  <button id="btn4" data-clipboard-target="block2" name ="btn4" type="button" class="btn btn-success"><i class="icon-white icon-file"></i> Copy</button>

  <script src="https://rawgit.com/zeroclipboard/zeroclipboard/master/dist/ZeroClipboard.js"></script>
</div>

<textarea id="block2" name="block2" style="font-family:rockwell; background-color:#D1D1D1"></textarea>

1 个答案:

答案 0 :(得分:0)

尝试:

<script language="JavaScript">
        var copyTextareaBtn = document.querySelector('.btn4');

copyTextareaBtn.addEventListener('click', function(event) {
  var copyTextarea = document.querySelector('.block2');
  copyTextarea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }
});
</script>