JavaScript复制到剪贴板不起作用

10 html javascript dom copy-paste

我的脚本中有一个函数给我一个错误.功能目的是使用onClick事件从静态面板(而不是文本框或输入)复制文本.

未捕获的TypeError:copyText.select不是函数

我想要的是让用户能够点击文本,然后将其复制到他的剪贴板.

也许你可以提供更好的功能吗?

https://codepen.io/abooo/pen/jYMMMN?editors=1010

function myFunction() {
  var copyText = document.getElementById("display");
  copyText.select();
  document.execCommand("Copy");
  alert("Copied the text: " + copyText.value);
}
Run Code Online (Sandbox Code Playgroud)

来自w3schools

Coo*_*ola 23

最近的解决方案(2020 年)使用了大多数现代浏览器都支持的新Clipboard API writeText 方法(有关更多详细信息,请参阅Can I use)。

//If you want to copyText from Element
function copyTextFromElement(elementID) {
  let element = document.getElementById(elementID); //select the element
  let elementText = element.textContent; //get the text content from the element
  copyText(elementText); //use the copyText function below
}

//If you only want to put some Text in the Clipboard just use this function
// and pass the string to copied as the argument.
function copyText(text) {
  navigator.clipboard.writeText(text);
}
Run Code Online (Sandbox Code Playgroud)
<div id="mytext">This is some text that needs to be copied</div>
<button onclick="copyTextFromElement('mytext')">Copy</button>
Run Code Online (Sandbox Code Playgroud)


Int*_*lia 11

这将允许您复制元素的文本.虽然我没有用复杂的布局测试它.

如果要使用此功能,请删除警报并提供更好的方法让用户知道内容已被复制.

SAFARI:这在版本10.0之前的Safari上不起作用.但是从Safari 10.0开始,现在可行了.

function copyText(element) {
  var range, selection, worked;

  if (document.body.createTextRange) {
    range = document.body.createTextRange();
    range.moveToElementText(element);
    range.select();
  } else if (window.getSelection) {
    selection = window.getSelection();        
    range = document.createRange();
    range.selectNodeContents(element);
    selection.removeAllRanges();
    selection.addRange(range);
  }
  
  try {
    document.execCommand('copy');
    alert('text copied');
  }
  catch (err) {
    alert('unable to copy text');
  }
}
Run Code Online (Sandbox Code Playgroud)
<h1 id='display' onClick='copyText(this)'>Text Sample</h1>
Run Code Online (Sandbox Code Playgroud)

如果你想在一个<input><textarea>元素上使用它,那么让我知道代码是不同的.

try/catch适用于旧版Safari,会引发异常.因此,如果您不打算在10.0版之前支持Safari,则可以将其删除.