【问题标题】:js copy function not working in htmljs复制功能在html中不起作用
【发布时间】:2018-06-15 05:21:15
【问题描述】:

我试图在我的 html 页面上获得一个复制按钮,但它不起作用 - 在 chrome 控制台中它什么也没说,它只是不会复制文本。

这是我的html:

<!doctype html>
<div class="ipDiv tk-saffran">
  <div class="ipText">
    <h2 id="ip">play.MineGlade.net</h2>
  </div>
  <div class="copyButton">
    <button onclick="copyIp()">Copy IP</button>
    <script>
      function copyIp() {
        var copyText = document.getElementById("ip");
        copyText.select;
        document.execCommand("Copy");
      }
    </script>
  </div>
</div>

我该如何解决这个问题?

【问题讨论】:

标签: javascript html copy


【解决方案1】:

您正在尝试选择不能与 select 函数一起使用的 h2 内容,而且您没有正确调用它,它应该是 .select()。要选择元素的内容,请检查this threadHow to select all text in contenteditable div?

请看fiddle我为你做的例子

    <div class="ipDiv tk-saffran">
        <div class="ipText">
            <h2 id="ip">play.MineGlade.net</h2>
        </div>
        <div class="copyButton">
            <button onclick="copyIp()">Copy IP</button>
            <script>
                jQuery.fn.selectText = function(){
                   var doc = document;
                   var element = this[0];
                   console.log(this, element);
                   if (doc.body.createTextRange) {
                       var range = document.body.createTextRange();
                       range.moveToElementText(element);
                       range.select();
                   } else if (window.getSelection) {
                       var selection = window.getSelection();        
                       var range = document.createRange();
                       range.selectNodeContents(element);
                       selection.removeAllRanges();
                       selection.addRange(range);
                   }
                };
                function copyIp() {
                   $("#ip").selectText();
                   document.execCommand("Copy");
                }
            </script>
        </div>
    </div>

确保你的包含 jquery 可以正常工作。

【讨论】:

    【解决方案2】:

    这是简单的方法进行复制,请查看此更新后的代码

    function copyIp()
    {
        window.getSelection().selectAllChildren(document.getElementById("ip"));
        document.execCommand("Copy");
    }
    <div class="ipDiv tk-saffran">
        <div class="ipText">
            <h2 id="ip">play.MineGlade.net</h2>
        </div>
        <div class="copyButton">
            <button onclick="copyIp()">Copy IP</button>
    
        </div>
    </div>

    【讨论】:

    • 那不是IP
    • @Luca 它是我的游戏服务器的服务器地址,在我的世界中它通常被称为 IP 地址,即使它是一个带有 DNS 记录以指向实际 IP 的域名。
    • @SanjayKumarSingh 我不知道如何“标记”答案,我对 stackoverflow 很陌生
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    相关资源
    最近更新 更多