JavaScript选择功能

JavaScript select function

本文关键字:功能 选择 JavaScript      更新时间:2023-11-12

我正在尝试使用JavaScript将文本复制到剪贴板。以下是到目前为止我得到的

var copyTextareaBtn = document.querySelector('#copy');
copyTextareaBtn.addEventListener('click', function(event) {
  var copyTextarea = document.getElementById('toCopy');
  copyTextarea.focus();
  copyTextarea.select();
  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
    alert("Link copied!");
  } catch (err) {
    alert("Unable to copy!");
  }
});

我得到一个错误,即copyTextarea.select不是一个函数。为什么?我百分之百确信JavaScript确实有一个select方法。

请确保id为"toCopy"的元素的类型为textarea