【问题标题】:How to copy String into Clipboard using a onClick Eventlistener如何使用 onClick 事件监听器将字符串复制到剪贴板
【发布时间】:2018-10-29 10:44:32
【问题描述】:

我的问题不是重复的,我没有使用 Jquery,我没有使用 textarea。我想使用 vanilla javascript 将变量的值复制到剪贴板中。

我想使用按钮的 onClick 事件监听器将存储在变量中的文本字符串复制到剪贴板。

我尝试修改此example,它使用输入字段,但它不起作用。我才刚刚开始了解 Javascript,所以请善待。我也在寻找不使用库的解决方案。

function myFunction() {
  var copyText = "This is a Test"
  copyText.select();
  document.execCommand("copy");

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

【问题讨论】:

  • copyText 只是一个字符串,而不是可选择的 HTML 元素
  • 真的!但是如何将变量的值放入剪贴板,而不必将其放入输入字段中?
  • 嘿 Mohammad,我没有使用 JQuery,我没有使用 textarea。我只是想知道如何使用 Vanilla javascript 将变量的值复制到剪贴板中,这可能是一个简单的问题,但它是一个有效的问题,并且与副本不同。

标签: javascript


【解决方案1】:

你可以试试这样的。

function myFunction() {
  // variable content to be copied
  var copyText = "Test"
  // create an input element
  let input = document.createElement('input');
  // setting it's type to be text
  input.setAttribute('type', 'text');
  // setting the input value to equal to the text we are copying
  input.value = copyText;
  // appending it to the document
  document.body.appendChild(input);
  // calling the select, to select the text displayed
  // if it's not in the document we won't be able to
  input.select();
  // calling the copy command
  document.execCommand("copy");
  // removing the input from the document
  document.body.removeChild(input)
}
<button onclick="myFunction()">Copy text</button>

【讨论】:

    【解决方案2】:

    HTMLInputElement.select() 方法选择元素中的所有文本或带有文本字段的元素。

    read more here.

    【讨论】:

      猜你喜欢
      • 2013-11-21
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-18
      • 2020-01-30
      • 1970-01-01
      相关资源
      最近更新 更多