Javascript 如何将文本从 div 复制到剪贴板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36639681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:20:52  来源:igfitidea点击:

How to copy text from a div to clipboard

javascriptjquery

提问by Alex

Here is my code for when the user clicks on this button:

这是用户单击此按钮时的代码:

<button id="button1">Click to copy</button>

How do I copy the text inside this div?

如何复制此 div 中的文本?

<div id="div1">Text To Copy</div>

回答by Eldho NewAge

Both examples work like a charm :)

这两个例子都像一个魅力:)

  1. JAVASCRIPT:

    function CopyToClipboard(containerid) {
      if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select().createTextRange();
        document.execCommand("copy");
      } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().addRange(range);
        document.execCommand("copy");
        alert("Text has been copied, now paste in the text-area")
      }
    }
    <button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>
    <br /><br />
    <div id="div1">Text To Copy </div>
    <br />
    <textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>

  2. JQUERY (relies on Adobe Flash): https://paulund.co.uk/jquery-copy-to-clipboard

  1. 爪哇脚本:

    function CopyToClipboard(containerid) {
      if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select().createTextRange();
        document.execCommand("copy");
      } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().addRange(range);
        document.execCommand("copy");
        alert("Text has been copied, now paste in the text-area")
      }
    }
    <button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>
    <br /><br />
    <div id="div1">Text To Copy </div>
    <br />
    <textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>

  2. JQUERY(依赖于 Adob​​e Flash):https: //paulund.co.uk/jquery-copy-to-clipboard

回答by J. García

I tried the solution proposed above. But it was not cross-browser enough. I really needed ie11 to work. After trying I got to:

我尝试了上面提出的解决方案。但这还不够跨浏览器。我真的需要 ie11 才能工作。尝试后我得到:

    <html>
        <body>
            <div id="a" onclick="copyDivToClipboard()"> Click to copy </div>
            <script>
                function copyDivToClipboard() {
                    var range = document.createRange();
                    range.selectNode(document.getElementById("a"));
                    window.getSelection().removeAllRanges(); // clear current selection
                    window.getSelection().addRange(range); // to select text
                    document.execCommand("copy");
                    window.getSelection().removeAllRanges();// to deselect
                }
            </script>
        </body>
    </html>

Tested with firefox 64, Chrome 71, Opera 57, ie11(11.472.17134.0), edge( EdgeHTML 17.17134)

使用 firefox 64、Chrome 71、Opera 57、ie11(11.472.17134.0)、edge(EdgeHTML 17.17134) 测试

Update March 27th, 2019.

2019 年 3 月 27 日更新。

For some reason document.createRange()didn't work before with ie11. But now properly returns a Range object. So is better to use that, rather than document.getSelection().getRangeAt(0).

由于某种原因,document.createRange()之前在 ie11 上不起作用。但现在正确返回一个 Range 对象。所以最好使用它,而不是document.getSelection().getRangeAt(0).

回答by romin21

The accepted answer does not work when you have multiple items to copy, and each with a separate "copy to clipboard" button. After clicking one button, the others will not work.

当您要复制多个项目并且每个项目都有一个单独的“复制到剪贴板”按钮时,接受的答案不起作用。单击一个按钮后,其他按钮将不起作用。

To make them work, I added some code to the accepted answer's function to clear text selections before doing a new one:

为了使它们工作,我在接受的答案的函数中添加了一些代码,以在执行新的文本选择之前清除文本选择:

function CopyToClipboard(containerid) {
    if (window.getSelection) {
        if (window.getSelection().empty) { // Chrome
            window.getSelection().empty();
        } else if (window.getSelection().removeAllRanges) { // Firefox
            window.getSelection().removeAllRanges();
        }
    } else if (document.selection) { // IE?
        document.selection.empty();
    }

    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select().createTextRange();
        document.execCommand("copy");
    } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().addRange(range);
        document.execCommand("copy");
    }
}

回答by loretoparisi

This solution add the deselection of the text after the copy to the clipboard:

此解决方案在复制到剪贴板后添加取消选择文本:

function copyDivToClipboard(elem) {
    var range = document.createRange();
    range.selectNode(document.getElementById(elem));
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
    document.execCommand("copy");
    window.getSelection().removeAllRanges();
}

回答by Arun Tom

I was getting selectNode() param 1 is not of type node error.

我得到 selectNode() param 1 is not type node error。

changed the code to this and its working. (for chrome)

将代码更改为此及其工作。(镀铬)

function copy_data(containerid) {
  var range = document.createRange();
  range.selectNode(containerid); //changed here
  window.getSelection().removeAllRanges(); 
  window.getSelection().addRange(range); 
  document.execCommand("copy");
  window.getSelection().removeAllRanges();
  alert("data copied");
}
<div id="select_txt">This will be copied to clipboard!</div>
<button type="button" onclick="copy_data(select_txt)">copy</button>
<br>
<hr>
<p>Try paste it here after copying</p>
<textarea></textarea>

回答by Aparna

Adding the link as an Answer to draw more attention to Aaron Lavers' comment below the first answer.

添加链接作为答案以吸引更多人关注 Aaron Lavers 在第一个答案下方的评论。

This works like a charm - http://clipboardjs.com. Just add the clipboard.js or min file. While initiating, use the class which has the html component to be clicked and just pass the id of the component with the content to be copied, to the click element.

这就像一个魅力 - http://clipboardjs.com。只需添加 clipboard.js 或 min 文件。在启动时,使用具有要单击的 html 组件的类,并将带有要复制的内容的组件的 id 传递给单击元素。

回答by AmaliaKalio

Made a modification to the solutions, so it will work with multiple divs based on class instead of specific IDs. For example, if you have multiple blocks of code. This assumes that the div class is set to "code".

对解决方案进行了修改,因此它将与基于类而不是特定 ID 的多个 div 一起使用。例如,如果您有多个代码块。这假设 div 类设置为“代码”。

<script>
        $( document ).ready(function() {
            $(".code").click(function(event){
                var range = document.createRange();
                range.selectNode(this);
                window.getSelection().removeAllRanges(); // clear current selection
                window.getSelection().addRange(range); // to select text
                document.execCommand("copy");
                window.getSelection().removeAllRanges();// to deselect
            });
        });
    </script>

回答by Sayed Azharuddin

Create a element to be appended to the document. Set its value to the string that we want to copy to the clipboard. Append said element to the current HTML document. Use HTMLInputElement.select() to select the contents of the element. Use Document.execCommand('copy') to copy the contents of the to the clipboard. Remove the element from the document

创建要附加到文档的元素。将其值设置为我们要复制到剪贴板的字符串。将所述元素附加到当前 HTML 文档中。使用 HTMLInputElement.select() 选择元素的内容。使用 Document.execCommand('copy') 将 的内容复制到剪贴板。从文档中删除元素

function copyToClipboard(containertext) {
    var el = document.createElement('textarea');
    el.value = containertext;
    el.text = containertext;
    el.setAttribute('id', 'copyText');
    el.setAttribute('readonly', '');
    el.style.position = 'absolute';
    el.style.left = '-9999px';
    document.body.appendChild(el);
    var coptTextArea = document.getElementById('copyText');
    $('#copyText').text(containertext);
    coptTextArea.select();
    document.execCommand('copy');
    document.body.removeChild(el);
    /* Alert the copied text */
    alert("Copied : "+containertext, 1000);
}

回答by iamafasha

Non of all these ones worked for me. But I found a duplicate of the question which the anaswer worked for me.

所有这些都不适合我。但是我发现了答案对我有用的问题的副本。

Here is the link

这是链接

How do I copy to the clipboard in JavaScript?

如何在 JavaScript 中复制到剪贴板?