从 <span> 复制文本到剪贴板

2022-01-20 00:00:00 复制 clipboard copy-paste javascript html

我一直在尝试将 <span>innerContent 复制到我的剪贴板,但没有成功:

I've been trying to copy the innerContent of a <span> to my clipboard without success:

<span id="pwd_spn" class="password-span"></span>

JavaScript

函数调用

    document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('copy').addEventListener('click', copy_password);
});

功能

function copy_password() {
    var copyText = document.getElementById("pwd_spn").select();
    document.execCommand("Copy");
}

我也试过了:

function copy_password() {
    var copyText = document.getElementById("pwd_spn").textContent;
    copyText.select();
    document.execCommand("Copy");
}

似乎 .select() 不适用于 <span> 元素,因为我在这两个元素上都收到以下错误:

It seems like .select() doesn't work on a <span> element since I get the following error on both:

推荐答案

您可以这样做:创建一个临时文本区域并将其附加到页面,然后将 span 元素的内容添加到文本区域,从文本区域复制值并删除文本区域.

You could do this: create a temporary text area and append it to the page, then add the content of the span element to the text area, copy the value from the text area and remove the text area.

由于某些安全限制,您只能在用户与页面交互时执行Copy命令,因此您必须添加一个按钮并在用户单击按钮后复制文本.

Because of some security restrictions you can only execute the Copy command if the user interacted with the page, so you have to add a button and copy the text after the user clicks on the button.

document.getElementById("cp_btn").addEventListener("click", copy_password);

function copy_password() {
    var copyText = document.getElementById("pwd_spn");
    var textArea = document.createElement("textarea");
    textArea.value = copyText.textContent;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand("Copy");
    textArea.remove();
}

<span id="pwd_spn" class="password-span">Test</span>
<button id="cp_btn">Copy</button>

相关文章