将JavaScript变量的输出复制到剪贴板

har*_*man 46 javascript clipboard copy

我不了解JavaScript,但我设法使用来自各种Stack Overflow答案的位和代码将这些代码放在一起.它工作正常,它通过警告框输出文档中所有选中复选框的数组.

function getSelectedCheckboxes(chkboxName) {
  var checkbx = [];
  var chkboxes = document.getElementsByName(chkboxName);
  var nr_chkboxes = chkboxes.length;
  for(var i=0; i<nr_chkboxes; i++) {
    if(chkboxes[i].type == 'checkbox' && chkboxes[i].checked == true) checkbx.push(chkboxes[i].value);
  }
  return checkbx;
}
Run Code Online (Sandbox Code Playgroud)

我称之为:

<button id="btn_test" type="button" >Check</button>
<script>
    document.getElementById('btn_test').onclick = function() {
        var checkedBoxes = getSelectedCheckboxes("my_id");
        alert(checkedBoxes);
    }
</script>
Run Code Online (Sandbox Code Playgroud)

现在我想修改它,所以当我单击btn_test按钮时,输出数组checkbx被复制到剪贴板.我尝试添加:

checkbx = document.execCommand("copy");
Run Code Online (Sandbox Code Playgroud)

要么

checkbx.execCommand("copy");
Run Code Online (Sandbox Code Playgroud)

在函数的最后,然后调用它:

<button id="btn_test" type="button" onclick="getSelectedCheckboxes('my_id')">Check</button>
Run Code Online (Sandbox Code Playgroud)

但它不起作用.没有数据复制到剪贴板.

wal*_*man 56

lbrutti对答案的想法很好,但他写错了代码!

function copyToClipboard(text) {
    var dummy = document.createElement("textarea");
    // to avoid breaking orgain page when copying more words
    // cant copy when adding below this code
    // dummy.style.display = 'none'
    document.body.appendChild(dummy);
    //Be careful if you use texarea. setAttribute('value', value), which works with "input" does not work with "textarea". – Eduard
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}
copyToClipboard('hello world')
copyToClipboard('hello\nworld')
Run Code Online (Sandbox Code Playgroud)

  • 这在 Chrome 中对任何人都有效吗?我在 v70+ 中,它不会抛出任何错误,但也不会复制。在 IE 中工作。 (3认同)

har*_*man 30

好的,我找到了一些时间并遵循了Teemu的建议,我能够得到我想要的.

所以这里是可能感兴趣的任何人的最终代码.为了澄清,此代码获取特定ID的所有选中复选框,将它们输出到数组中,在此处命名checkbx,然后将其唯一名称复制到剪贴板.

JavaScript函数:

function getSelectedCheckboxes(chkboxName) {
  var checkbx = [];
  var chkboxes = document.getElementsByName(chkboxName);
  var nr_chkboxes = chkboxes.length;
  for(var i=0; i<nr_chkboxes; i++) {
    if(chkboxes[i].type == 'checkbox' && chkboxes[i].checked == true) checkbx.push(chkboxes[i].value);
  }
  checkbx.toString();

  // Create a dummy input to copy the string array inside it
  var dummy = document.createElement("input");

  // Add it to the document
  document.body.appendChild(dummy);

  // Set its ID
  dummy.setAttribute("id", "dummy_id");

  // Output the array into it
  document.getElementById("dummy_id").value=checkbx;

  // Select it
  dummy.select();

  // Copy its contents
  document.execCommand("copy");

  // Remove it as its not needed anymore
  document.body.removeChild(dummy);
}
Run Code Online (Sandbox Code Playgroud)

它的HTML调用:

<button id="btn_test" type="button" onclick="getSelectedCheckboxes('ID_of_chkbxs_selected')">Copy</button>
Run Code Online (Sandbox Code Playgroud)

  • 这可以在不创建HTML元素的情况下完成吗?比方说,我只是想在单击按钮或预先指定的元素时将字符串复制到用户剪贴板? (7认同)
  • 我建议使用"textarea"而不是"input",这样你也可以复制换行符. (4认同)

lbr*_*tti 13

很有用.我修改它以将JavaScript变量值复制到剪贴板:

function copyToClipboard(val){
    var dummy = document.createElement("input");
    dummy.style.display = 'none';
    document.body.appendChild(dummy);

    dummy.setAttribute("id", "dummy_id");
    document.getElementById("dummy_id").value=val;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}
Run Code Online (Sandbox Code Playgroud)

  • 更改$(dummy).css('display','none'); 进入dummy.style.display ='none'; 避免jQuery (2认同)
  • Chrome需要显示虚拟对象。所以我删除了一行代码,它可以正常工作,谢谢 (2认同)

小智 13

为了将任何文本复制到剪贴板的一般目的,我编写了以下函数:

function textToClipboard (text) {
    var dummy = document.createElement("textarea");
    document.body.appendChild(dummy);
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}
Run Code Online (Sandbox Code Playgroud)

将参数的值插入到新创建的值中<textarea>,然后选择该值,将其值复制到剪贴板,然后从文档中删除它.


Adi*_*tya 11

使用剪贴板 API

text = "HEllo World";
navigator.clipboard.writeText(text)
Run Code Online (Sandbox Code Playgroud)

它适用于 Chrome 66+、Edge 79+、Firefox 63+,不适用于 IE

在MDN 文档中阅读有关剪贴板 API 的更多信息


Evg*_*eny 8

当您需要在 Chrome 开发者控制台中将变量复制到剪贴板时,您只需使用该copy()命令即可。

https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#copyobject


Ped*_*ito 7

我设法通过向 中添加隐藏元素来将文本复制到剪贴板(不显示任何文本框),即: inputbody

 function copy(txt){
  var cb = document.getElementById("cb");
  cb.value = txt;
  cb.style.display='block';
  cb.select();
  document.execCommand('copy');
  cb.style.display='none';
 }
Run Code Online (Sandbox Code Playgroud)
<button onclick="copy('Hello Clipboard!')"> copy </button>
<input id="cb" type="text" hidden>
Run Code Online (Sandbox Code Playgroud)


Pie*_*nry 5

现在有一个新的(ish)API可以直接执行此操作。它仅适用于现代浏览器和 HTTPS(和本地主机)。IE11 不支持。

IE11 有自己的 API。

接受的答案中的解决方法可用于不安全的主机。

function copyToClipboard (text) {
  if (navigator.clipboard) { // default: modern asynchronous API
    return navigator.clipboard.writeText(text);
  } else if (window.clipboardData && window.clipboardData.setData) {     // for IE11
    window.clipboardData.setData('Text', text);
    return Promise.resolve();
  } else {
    // workaround: create dummy input
    const input = h('input', { type: 'text' });
    input.value = text;
    document.body.append(input);
    input.focus();
    input.select();
    document.execCommand('copy');
    input.remove();
    return Promise.resolve();
  }
}
Run Code Online (Sandbox Code Playgroud)

注意:它使用 Hyperscript 来创建输入元素(但应该很容易适应)

没有必要使输入不可见,因为它的添加和删除速度非常快。此外,当隐藏(甚至使用一些聪明的方法)时,一些浏览器会检测到它并阻止复制操作。