如何复制多个输入

问题描述 投票:1回答:4

大家好,我如何通过许多输入执行复制到剪贴板的操作?我有此代码

HTML代码

<input type="text" value="Hello" id="myInput1">
<input type="text" value="World" id="myInput2">

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

SCRIPT CODE

<script>
function myFunction() {
  var copyText1 = document.getElementById("myInput1");
  var copyText2 = document.getElementById("myInput1");
  copyText1.select();
  copyText1.setSelectionRange(0, 99999)
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
</script>

我希望有人帮助我。谢谢大家!

javascript php jquery html css
4个回答
0
投票

您可以使用隐藏字段来存储所有值,然后在该隐藏字段上执行命令:

<input type="text" value="Hello" id="myInput1">
<input type="text" value="World" id="myInput2">

<button onclick="myFunction()">Copy text</button>
<input type="hidden" value="" id="output">


<script>
function myFunction() {
  var copyText1 = document.getElementById("myInput1");
  var copyText2 = document.getElementById("myInput2");
  var res = document.getElementById("output")
  res.value = copyText1.value + " " + copyText2.value;
  res.select();
  //res.setSelectionRange(0, 99999)
  document.execCommand("copy");
  alert("Copied the text: " + res.value);
}
</script>

0
投票

为此,您可以添加第三个输入字段,然后将其隐藏即可。并且,在执行文本选择和复制命令之前,请取消隐藏输入,然后再次将其隐藏。

function myFunction() {
    var copyText1 = document.getElementById("myInput1");
    var copyText2 = document.getElementById("myInput2");
    var hiddenInput = document.getElementById("hiddenInput");
    hiddenInput.value='Description1: '+copyText1.value+' Description2: '+copyText2.value;
    hiddenInput.style.display='';
    hiddenInput.select();
    hiddenInput.setSelectionRange(0, 99999);
    document.execCommand("copy");
    hiddenInput.style.display='none';
    alert("Copied the text: " + hiddenInput.value);
}
<input type="text" value="Hello" id="myInput1">
<input type="text" value="World" id="myInput2">
<input type="text" id="hiddenInput" style="display:none;">
    
<button onclick="myFunction()">Copy text</button>

-1
投票

使用querySelectorAll选择所有输入,进行循环,然后在每个输入上执行复制命令。

function myFunction() {
  const inputs = document.querySelectorAll('input');
  inputs.forEach((input, i) => {
    input.select();
    document.execCommand('copy');
    console.log('description:' + (i + 1), input.value);
  });
}
<input type="text" value="Hello" id="myInput1">
<input type="text" value="World" id="myInput2">

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

-1
投票

您可以获取输入值并将其作为第三个参数发送到execCommand。

    <input type="text" value="Hello" id="myInput1">
    <input type="text" value="World" id="myInput2">

    <button onclick="myFunction()">Copy text</button>
    <script>
      function myFunction() {
        const inputs = document.querySelectorAll('input');
        const copiedValue = [].map.call(inputs,(input) => input.value || '').join('');
        document.execCommand("copy", false ,copiedValue);
        alert("Copied the text: " + copiedValue);
      }
    </script>
© www.soinside.com 2019 - 2024. All rights reserved.