首页 > 解决方案 > 单击文本时将文本复制到剪贴板的脚本

问题描述

我对以下脚本有疑问:

function copyElementText(id) {
        var text = document.getElementById(id).innerText;
        var elem = document.createElement("textarea");
        document.body.appendChild(elem);
        elem.value = text;
        elem.select();
        document.execCommand("copy");
        document.body.removeChild(elem);
        console.log('Copy made');
    }
    <font id="text" onclick="copyElementText(this.id)">Copy this text</font>

当您单击它时,此脚本会将文本复制到剪贴板。

我只能使用一次。我需要在 HTML 文件中多次使用它。如何调整脚本以便我可以多次使用它?

谢谢!

标签: javascripthtml

解决方案


  1. 首先,您的代码在一个文本上运行良好。
  2. 其次,你应该关心Id属性

因此,要解决它,您应该添加另一个具有不同ID属性的文本,如下所示。

id属性是用于指定文档的唯一标识符

function copyElementText(id) {
    var text = document.getElementById(id).innerText;
    var elem = document.createElement("textarea");
    document.body.appendChild(elem);
    elem.value = text;
    elem.select();
    document.execCommand("copy");
    document.body.removeChild(elem);
    
    console.log(text);
}
<font id="text1" onclick="copyElementText(this.id)">Copy this text</font>
<font id="text2" onclick="copyElementText(this.id)">Copy another text</font>

如果有很多<font>标签,那么最好使用 aclass而不是id像下面这样

function copyElementText(event) {
    var text = event.innerText;
    
    var elem = document.createElement("textarea");
    document.body.appendChild(elem);
    elem.value = text;
    elem.select();
    document.execCommand("copy");
    document.body.removeChild(elem);
    
    console.log(text);
}
<font class="text" onclick="copyElementText(this)">Copy this text</font>
 <font class="text" onclick="copyElementText(this)">Copy another text</font>


推荐阅读