【问题标题】:How to paste data from clipboard to multiple input fields?如何将剪贴板中的数据粘贴到多个输入字段?
【发布时间】:2020-01-28 19:38:32
【问题描述】:

如何使用多个输入执行复制到剪贴板?我有这个代码

HTML 代码

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

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

脚本代码

<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>

【问题讨论】:

  • 您想如何将这些保存在剪贴板中?比如myInput1myInput2?
  • @VermaJr。如果可能的话,我能不能有这种格式: "Description1: " myInput1 "Description2: " myInput2 带引号的都是静态的,每个都应该换行。

标签: javascript jquery html


【解决方案1】:

您可以添加第三个输入字段(或 textarea,如果您还想添加换行符)并简单地隐藏它。并且,在执行文本选择和复制命令之前,取消隐藏文本区域,然后再次隐藏它。

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

【讨论】:

  • 即使我需要对所有 @_@ 进行硬编码也能正常工作。谢谢
【解决方案2】:

也许是这个?
更多剪贴板使用信息 => https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard#Using_the_Clipboard_API

btCopy.onclick=_=>
  {
  // step 1: collect the input values (a method like so many others)
  let inputs = {}
  Array.from(new FormData(myForm),entry=>{inputs[ entry[0] ] = entry[1]})
  let All_inputs = JSON.stringify(inputs)

  // step 2 : write All_inputs into the clipboard
  navigator.clipboard.writeText(All_inputs)

  // as in your wishes...
  alert('Copied the text: ' + All_inputs)
  }
<form id="myForm">
  <input type="text" name="Description1" value="Hello">
  <input type="text" name="Description2" value="world">
</form>

<button id="btCopy">copy</button>

【讨论】:

  • 如果您提供解释,您很可能会获得支持和接受。并且不要使用旧方法假设 id 作为变量存在,这是不好的做法。
  • @LGSon 您混淆了所谓的不良做法只是一种观点。在任何情况下,对元素使用名称或 ID 对该代码没有任何影响。作为记录:我总是使用表单元素族的名称,因为它们是用于序列化函数的名称,而不是 ID。
  • 那么您可能想阅读以下内容:stackoverflow.com/a/19776647/2827823 ... 而不是接受众所周知的事情,而是反对它。另一个是这样的:stackoverflow.com/questions/6348494/addeventlistener-vs-onclick
  • 鉴于未来的用户应该从这里的答案中学习,最合适的会被投票,其他的不会,我认为当你进入未知的编码领域时你会想要同样的(获得更多合适的)。
  • 根据你的链接,很明显你没有读过我的,所以我会休息一下。
猜你喜欢
  • 2020-07-11
  • 1970-01-01
  • 1970-01-01
  • 2022-06-23
  • 1970-01-01
  • 2019-04-16
  • 2010-09-24
  • 2012-11-06
  • 2017-12-23
相关资源
最近更新 更多