简体   繁体   English

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

[英]Copy text to clipboard from div with javascript

I'm trying to copy the text from the next div to the clipboard with Javascript .我正在尝试使用Javascript将文本从下一个 div 复制到剪贴板。 Below is my current code:以下是我当前的代码:

HTML: 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: Javascript:

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

I'm expecting to get the new output when I paste it into the notepad :当我将它粘贴到notepad时,我希望得到新的输出:

1
2
3
4
5
6
7
8

However, for some reason, it's not working and throw the next error message :但是,由于某种原因,它不起作用并抛出下一条错误消息:

Uncaught TypeError: copyText.select is not a function ...未捕获的类型错误:copyText.select 不是函数...

Does anyone know how could I solve this issue?有谁知道我该如何解决这个问题?

First, some reference:首先,一些参考:

The getElementsByClassName() method of Document interface returns an array-like object of all child elements which have all of the given class names. Document 接口的getElementsByClassName()方法返回具有所有给定类名的所有子元素的类数组对象 When called on the document object, the complete document is searched, including the root node.当在文档对象上调用时,将搜索完整的文档,包括根节点。 You may also call getElementsByClassName() on any element;你也可以在任何元素上调用getElementsByClassName() it will return only elements which are descendants of the specified root element with the given class names.它将只返回具有给定类名的指定根元素的后代元素。

So, in your particular case, the copyText variable will hold an array of elements (those that have the class hl7MsgBox under the document element).因此,在您的特定情况下, copyText变量将保存一个元素数组(那些在文档元素下具有hl7MsgBox类的元素)。 Now, because in your case there is only one element with that class, you can access it using copyText[0] and get all the text wrapped by it with copyText[0].textContent .现在,因为在你的情况下,只有一个元素与类,你可以使用访问它copyText[0]并得到所有被它包裹着文字copyText[0].textContent In summary, you can do something like next to get the text to be copied:总之,您可以执行类似 next 的操作来获取要复制的文本:

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

Another possibility is to use the method querySelector() :另一种可能性是使用方法querySelector()

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. Document 方法querySelector()返回文档中与指定选择器或选择器组匹配的第一个元素 If no matches are found, null is returned.如果未找到匹配项,则返回null

With the querySelector() method you can simply do:使用querySelector()方法,您可以简单地执行以下操作:

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

Finally, we can create a general method called copyToClipBoard() whose only job is to copy the received string to the clipboard an rearrange the code with pure Javascript like this:最后,我们可以创建一个称为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>

Simply get the text from the DIV and pass it into this function.只需从 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM