使用JavaScript从div复制文本到剪贴板

5
我是一个有用的助手,可以翻译文本。
我正在尝试使用JavaScript将下一个
中的文本复制到剪贴板。以下是我的当前代码:
HTML:
<div class="hl7MsgBox">
    <span class="boxspan">1</span>
    <br>
    <span class="boxspan">2</span>
    <br>
    <span class="boxspan">3</span>
    <br>
    <span class="boxspan">4</span>
    <br>
    <span class="boxspan">5</span>
    <br>
    <span class="boxspan">6</span>
    <br>
    <span class="boxspan">7</span>
    <br>
    <span class="boxspan">8</span>
</div>

Javascript:

$(".btnFileCopy").click(function () {
    var copyText = document.getElementsByClassName("hl7MsgBox");
    copyText.select();
    document.execCommand("copy");
});

当我将其粘贴到记事本中时,我期望能够获得新的输出:

1
2
3
4
5
6
7
8

然而,由于某种原因,它无法正常工作并抛出以下错误信息:

Uncaught TypeError: copyText.select is not a function ...

有人知道如何解决这个问题吗?

可能是querySelectorAll和getElementsBy*方法返回什么?的重复问题。 - Sebastian Simon
可能是重复的问题:Javascript - 点击复制文本字符串 - kgbph
2个回答

13

首先,一些参考资料:

Document接口的getElementsByClassName()方法返回一个类数组对象,其中包含所有具有给定类名的子元素。当在文档对象上调用时,将搜索完整的文档,包括根节点。您也可以在任何元素上调用getElementsByClassName();它只会返回具有给定类名的指定根元素的后代元素。

所以,在您的特定情况下,copyText变量将保存一个元素数组(那些在文档元素下具有hl7MsgBox类的元素)。现在,在您的情况下只有一个具有该类的元素,您可以使用copyText[0]访问它,并使用copyText[0].textContent获取其包装的所有文本。总之,您可以执行以下操作以获取要复制的文本:

var elems = document.getElementsByClassName("hl7MsgBox");
var copyText = elems[0].textContent;

另一种可能性是使用方法querySelector():

文档方法querySelector()返回与指定选择器或选择器组匹配的第一个元素。如果没有找到匹配项,则返回null

使用querySelector()方法,您可以很简单地执行以下操作:

var copyText = document.querySelector(".hl7MsgBox").textContent;

最后,我们可以创建一个名为copyToClipBoard()的通用方法,其唯一任务是将接收到的string复制到剪贴板并使用纯Javascript重新排列代码,如下所示:

const copyToClipBoard = (str) =>
{
    const el = document.createElement('textarea');
    el.value = str;
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
};

document.querySelector(".btnCopy").addEventListener("click", function()
{
    var copyText = document.querySelector(".hl7MsgBox").textContent;

    // Or...
    //var elems = document.getElementsByClassName("hl7MsgBox");
    //var copyText = elems[0].textContent;

    copyToClipBoard(copyText);
});
<div class="hl7MsgBox">
    <span class="boxspan">1</span>
    <br>
    <span class="boxspan">2</span>
    <br>
    <span class="boxspan">3</span>
    <br>
    <span class="boxspan">4</span>
    <br>
    <span class="boxspan">5</span>
    <br>
    <span class="boxspan">6</span>
    <br>
    <span class="boxspan">7</span>
    <br>
    <span class="boxspan">8</span>
</div>
<button class="btnCopy">Copy To Clipboard</button>
<br>
<textarea rows=8 cols=50 placeholder="Paste text here..."></textarea>


请注意,更完整和通用的copyToClipboard函数可以在此处找到:https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f - sstruct

3
简单地从DIV中获取文本并将其传递到此函数中。
function copyToClipboard(text) {
    if (window.clipboardData && window.clipboardData.setData) {
        // IE specific code path to prevent textarea being shown while dialog is visible.
        return clipboardData.setData("Text", text); 

    } else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in MS Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            return document.execCommand("copy");  // Security exception may be thrown by some browsers.
        } catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return false;
        } finally {
            document.body.removeChild(textarea);
        }
    }
}   

copyToClipboard('hello'); //hello

1
唯一起作用的代码。@Diego Fortes 这里有很棒的东西。 - Leo Santos

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