我的脚本中有一个函数,给我一个错误。该功能的目的是通过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);
}

从w3schools

最佳答案

这将允许您复制元素的文本。虽然我没有用复杂的布局对其进行测试。

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



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');
  }
}
<h1 id='display' onClick='copyText(this)'>Text Sample</h1>


如果要在<input><textarea>元素上使用此代码,请告诉我代码是不同的。

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

09-27 00:55
查看更多