从 <span> 复制文本到剪贴板 [英] Copy text from <span> to clipboard

查看:43
本文介绍了从 <span> 复制文本到剪贴板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将 <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>

这篇关于从 &lt;span&gt; 复制文本到剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆