使用JavaScript将多个输入值复制到剪贴板

时间:2018-10-03 00:09:56

标签: javascript html

在我的代码中,我有3个输入字段。我想将这些输入字段中的值复制到由下划线分隔的剪贴板中。

示例:红色_蓝色_黑色

问题是,我的代码仅复制输入之一,并且在复制时我不知道如何用下划线分隔值。

<!DOCTYPE html>
<html>
    <body>

    <p>Click on the button to copy the text from the text field. Try to paste the text (e.g. ctrl+v) afterwards in a different window, to see the effect.</p>

    <input type="text" value="Red" id="myInput">
    <input type="text" value="Blue" id="myInput2">
    <input type="text" value="Black" id="myInput3">

    <button onclick="myFunction()">Copy text</button>

    <p>The document.execCommand() method is not supported in IE8 and earlier.</p>

    <script>
    function myFunction() {
      var copyText = document.getElementById("myInput");
      var copyText2 = document.getElementById("myInput2");
      var copyText2 = document.getElementById("myInput3");
      copyText.select();
      copyText2.select();
      copyText3.select();
      document.execCommand("copy");

    }
    </script>

    </body>
</html>

2 个答案:

答案 0 :(得分:2)

看起来这样不可能直接,因为您只能将当前选择的内容复制到clipbord。有一种解决方法,可以写入隐藏的输入,选择该输入然后复制:

<input type="text" value="Red" id="myInput">
<input type="text" value="Blue" id="myInput2">
<input type="text" value="Black" id="myInput3">
<input type="text" value="" id="output">
<button onclick="myFunction()">Copy text</button>
<script>
    function myFunction() {
      var copyText = document.getElementById("myInput");
      var copyText2 = document.getElementById("myInput2");
      var copyText3 = document.getElementById("myInput3");
      var output = document.getElementById("output");
      output.value = copyText.value + "_" + copyText2.value + "_" + copyText3.value;
      output.select();
      document.execCommand("copy");

    }
</script>

A fiddle

编辑: 在隐藏输出输入之前,我做了测试。它不适用于隐藏的输入。使用How do I copy to the clipboard in JavaScript?

中的答案

答案 1 :(得分:0)

基于Jeff的答案,我隐藏了输入字段,因此它“似乎是一个隐藏字段”。我这样做是因为您似乎无法选择并获取隐藏字段的值。

.txt-invisible {
    border: none;
    width: 0px;
    height: 0px;
    color: transparent;
}

    .txt-invisible:focus {
        outline: none;
    }
    <input type="text" value="Red" id="myInput">
    <input type="text" value="Blue" id="myInput2">
    <input type="text" value="Black" id="myInput3">
    <input type="text" value="" id="output" class="txt-invisible">
    <button onclick="myFunction()">Copy text</button>
<script>
    function myFunction() {
      var copyText = document.getElementById("myInput");
      var copyText2 = document.getElementById("myInput2");
      var copyText3 = document.getElementById("myInput3");
      var output = document.getElementById("output");
      output.value = copyText.value + "_" + copyText2.value + "_" + copyText3.value;
			output.select();
      document.execCommand("copy");

    }
</script>