代码之家  ›  专栏  ›  技术社区  ›  GYaN user7305435

当输入字段隐藏时,jquery将文本复制到剪贴板

  •  0
  • GYaN user7305435  · 技术社区  · 6 年前

    我想复制剪贴板中输入字段的内容

    我的代码是

    <button class="btn btn-default btn-xs copy-link" title="Copy Link"><i class="fa fa-copy"></i></button>
    <input type="text" class="link" value="Hello World">
    
    <script>
        $(document).on('click','.copy-link', function() {
            var copyText = $(this).siblings('.link');
            copyText.select();
            document.execCommand("copy");
            alert("Copied the text: " + copyText.val());
        });
    </script>
    

    这个代码运行良好…

    但我想隐藏输入字段。喜欢

     <button class="btn btn-default btn-xs copy-link" title="Copy Link"><i class="fa fa-copy"></i></button>
    <input type="hidden" class="link" value="Hello World" />
    

    然后该值不处理同一个jquery…

    我还缺什么吗?

    3 回复  |  直到 6 年前
        1
  •  2
  •   Takit Isy    6 年前

    如果您可以将链接放入按钮中的链接属性中,

    我建议你如下:

    • 移除你的 input 从html
    • 直接在函数中创建

    下面是一个工作片段:

    $(document).on('click', '.copy-link', function() {
      var link = $(this).attr('link');
      var tempInput = document.createElement("input");
      tempInput.style = "position: absolute; left: -1000px; top: -1000px";
      tempInput.value = link;
      document.body.appendChild(tempInput);
      tempInput.select();
      document.execCommand("copy");
      console.log("Copied the text:", tempInput.value);
      document.body.removeChild(tempInput);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">
    
    <button class="btn btn-default btn-xs copy-link" title="Copy Link" link="Hello World"><i class="fa fa-copy"></i></button>

    希望有帮助。

        2
  •  1
  •   GYaN user7305435    6 年前

    尝试不透明度0; 在这里,它确实起作用;)

    <input type="text" class="link hidden" value="Hello World 2">
    .hidden {
      position:absolute; top:-50px; opacity:0;
    }
    

    https://jsfiddle.net/o2gxgz9r/47741/

        3
  •  0
  •   Himanshu Upadhyay    6 年前

    应用下面提到的样式,然后使用相同的jquery代码。它会起作用的。

    <input type="text" class="link hidden" value="Hello World 2" style="position: absolute; left: -1000px;">