将文本js复制到剪贴板

时间:2018-04-28 05:34:46

标签: javascript

我有:

HTML code:

<div class="server-ip clearfix">
<p>
  <i class="ion-ios-world"></i>
  <span id="serv-1">play.minesuperior.com</span>
</p>
<a class="copy-action" href="#!" onclick="copyText('serv-1')">
    <span class="copy-text">
      <i class="ion-scissors"></i>
      Copy
    </span>
</a>
</div>

JS功能:

function copyText(textToCopy) {
  var copyText = document.getElementById(textToCopy).textContent;
  console.log(copyText);

  copyText.select();
  document.execCommand("Copy");

  alert("Copied the text: " + copyText);
}

我收到错误:

Uncaught TypeError: copyText.select is not a function

为什么呢?在函数中,我传递了参数:play.minesuperior.com。 我试着在console.log中输入param函数,然后得到我的文本。

1 个答案:

答案 0 :(得分:3)

尝试下面的代码段,

&#13;
&#13;
function CopyToClipboard(containerid) {

    var range = document.createRange();
     range.selectNode(document.getElementById(containerid));
     window.getSelection().addRange(range);
     document.execCommand("copy");
     alert("text copied") ;
}
&#13;
<div class="server-ip clearfix">
                <p>
                  <i class="ion-ios-world"></i>
                  <span id="serv-1">play.minesuperior.com</span>
                </p>
                <a class="copy-action" href="#!" onclick="CopyToClipboard('serv-1')">
                    <span class="copy-text">
                      <i class="ion-scissors"></i>
                      Copy
                    </span>
                </a>
  </div>
&#13;
&#13;
&#13;