JavaScript复制到剪贴板不起作用

25

我的脚本中有一个函数出现了错误。这个函数的目的是从静态面板(不是文本框或输入框)复制文本,具有 onClick 事件。

Uncaught TypeError: copyText.select is not a function

我想要的是让用户能够点击文本并将其复制到剪贴板。

也许你可以提供一个更好的可行函数吗?

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


<h1> 没有 .value() 函数(也没有 .select() 函数)。也许您想到的是输入框? - Blue
h1 更改为 textarea,例如...这样它就可以工作了。 - Hackerman
1
不需要将header1标签替换为textarea。您可以使用隐藏输入来保存调用函数的元素的textContent,这将使您能够使用.select()document.execCommand('copy') CodePen示例 已更新以供多次使用 - NewToJS
6个回答

29

您可以使用大多数现代浏览器支持的新剪贴板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);
}
<div id="mytext">This is some text that needs to be copied</div>
<button onclick="copyTextFromElement('mytext')">Copy</button>


24

这将允许您复制元素的文本。尽管我没有测试过它在复杂的布局中的表现。

如果您想使用此功能,请删除警告并提供更好的方法来让用户知道内容已被复制。

SAFARI: 在 Safari 10.0 之前,此功能无法使用。但是自从 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');
  }
}
<h1 id='display' onClick='copyText(this)'>Text Sample</h1>

如果你想在 <input><textarea> 元素上使用此代码,请告诉我,因为代码会有所不同。

try/catch 是为了兼容早期版本的 Safari 而添加的异常处理机制。因此,如果你不打算支持 10.0 版本之前的 Safari,则可以将其删除。


我认为在该命令上使用trycatch并不重要。即使您没有正确选择文本,它也不会复制任何内容或者只会复制您实际选择的内容。 - zfrisch
但是如果尝试复制电子邮件内容,这种方法将无法正常工作。 - Dhaval Panchal
try/catch 在旧版浏览器中是必需的。其中一些浏览器会抛出异常而不是优雅地失败。 - Intervalia

3

Intervalia的回答很好。

但有时点击的元素不是要复制的元素。
因此,我建议您传递要复制的元素的id。

<button onClick='copyText("display")'> Copy </button>
<h1 id='display'> Text Sample </h1>

然后,在您的函数的第一行执行以下操作:

element = document.getElementById(element); 

虽然区别不大,但我认为这样更有用。


2

select()方法用于选择文本字段的内容。它不适用于h1元素。


0

hi so I looked into it and since you are not using a textInput you cannot just use the .select()function. I borrowed some code from a fellow stack overflow developer Jason on how to highlight an item in javaScript

selecting text in an element akin to highlighting with your mouse.

function selectedText(element)(){

var doc = document,
text = doc.getElementById(element)
range, selection;

if(doc.body.createTextRange){ 
 range = document.body.createTextRange();
 range.moveToElementText(text);
 range.select(); 
}
else if(window.getSelection){
  selection = window.getSelection();
  range = document.createRange();
  range.selectNodeContents(text);
  selection.removeAllRanges();
  selection.addRange(range);   
}

return range;

然后我修改了它以返回范围。 这样你所要做的就是

document.onclick = function(e){
  if(e.target.className === 'click'){

      var copytext = SelectText('display');
      document.execCommand("copy");
      alert("Copied the text: " + copytext);
   }
}

这里的关键部分是传递给.execCommand() 的字符串是小写的'copy'


-1

我正在使用这个。这与其他答案类似,但在Chrome中似乎有效。

function CopyToClipBoard(textToCopy) {
var successMessage = 'Success! The text was copied to your clipboard';
var errorMessage = 'Oops! Copy to clipboard failed. ';

// navigator clipboard api needs a secure context (https)
if (navigator.clipboard && window.isSecureContext) {

    // navigator clipboard api method'
    navigator.clipboard.writeText(textToCopy).then(
        function () {
            /* clipboard successfully set */
            console.log(successMessage)
        },
        function () {
            /* clipboard write failed */
            console.warn(errorMessage)
        }
    )
} else
    if (document.queryCommandSupported && document.queryCommandSupported("copy")) {

    // text area method
    var textarea = document.createElement("textarea");
    textarea.value = textarea.textContent = textToCopy;
    textarea.style.opacity = "0"; 

    document.body.appendChild(textarea);
    textarea.focus();
        textarea.select();

        var selection = document.getSelection();
        var range = document.createRange();
        
        range.selectNode(textarea);
        selection.removeAllRanges();
        selection.addRange(range);

    try {
        var successful = document.execCommand('copy'); // Security exception may be thrown by some browsers.
        var msg = successful ? console.log(successMessage) : console.warn(errorMessage);
    }
    catch (ex) {
        console.warn(errorMessage, ex);
    }
    finally {
        selection.removeAllRanges();
        document.body.removeChild(textarea);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接