如何将div中的文本复制到剪贴板

105

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

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

我该如何复制这个 DIV 中的文本?

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

6
从一个 DIV 而非文本区域。 - Alex
4
仅使用JS的解决方案,详见http://jsfiddle.net/jdhenckel/km7prgv4/3。 - John Henckel
1
这个链接是一个关于编程的内容,讲述了如何解决一个问题。它提供了一个有效的解决方案,并且被其他开发者证实可行。 - Eric
11个回答

141

我尝试了上面提出的解决方案。但它不够跨浏览器兼容。我确实需要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>

已在Firefox 64、Chrome 71、Opera 57、IE11(11.472.17134.0)和Edge(EdgeHTML 17.17134)中进行测试。

更新于2019年3月27日。

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


7
这应该是这个帖子中最佳的答案。经过数小时的寻找一个可行的解决方案,最终这个方法对我起作用了。谢谢。 :-) - Himanshu Aggarwal
1
提示:在复制命令后添加另一个 window.getSelection().removeAllRanges(); 来取消选择已复制的内容。 - stardust4891
好的,让我们把它加入到答案中。 - J. García
这是使用“范围”选择的简化示例,它并不打算涵盖所有边角情况。主要展示了使用Range类的一种方式。您能否更具体一些或者发布另一个问题,说明您的确切用例?我自己使用基于“范围”的“选择”与多个“divs”/“element” 。我强烈建议检查“范围”API,并查看它提供的任何其他函数是否有所帮助。 - J. García
这在2022年运行良好。 - Vinicius
显示剩余2条评论

103

这两个示例都非常有效 :)

  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


8
补充一下这个答案,我使用过一个很棒的插件,可以处理这个问题:https://clipboardjs.com/ - Aaron Lavers
15
第一项无法正常工作。 - Alex
2
请告诉我第一个示例如何工作。 - Alex
2
希望它能够正常工作。在Firefox和Chrome中进行了检查。 - Eldho NewAge
4
在调用window.getSelection().addRange(range)之前,请先调用此方法window.getSelection().removeAllRanges()。 - yondoo
显示剩余12条评论

24

如果你有多个要复制的项目,且每个项目都有一个单独的“复制到剪贴板”按钮,则接受的答案将无法正常工作。在点击一个按钮后,其他按钮将无法工作。

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

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");
    }
}

10

我一直收到“selectNode()参数1的类型不是节点”的错误。

将代码更改为以下内容后,它可以正常工作。(适用于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>


6

这个解决方案可以在复制到剪贴板后取消选定文本:

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();
}

5

这里有一段代码,可以在不同的浏览器中运行,包括iOS。

const copyToClipboard = (id) => {
  var r = document.createRange();
  r.selectNode(document.getElementById(id));
  window.getSelection().removeAllRanges();
  window.getSelection().addRange(r);
  document.execCommand("copy");
  window.getSelection().removeAllRanges();
};

const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;

const copyIOS = (id) => {
  const text = document.getElementById(id).innerHTML;

  if (!navigator.clipboard) {
    const textarea = document.createElement("textarea");

    textarea.value = text;
    textarea.style.fontSize = "20px";
    document.body.appendChild(textarea);

    const range = document.createRange();
    range.selectNodeContents(textarea);

    const selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    textarea.setSelectionRange(0, 999999);

    document.execCommand("copy");

    document.body.removeChild(textarea);
  }

  navigator.clipboard.writeText(text);
};

const copyTextById = (id) => {
  if (isIOS) {
    return copyIOS(id);
  }
  copyToClipboard(id);
};

window.copyTextById = copyTextById
<div id="text">Text which you will copy</div>

<button onclick="copyTextById('text')">Click me</button>


5
<div id='myInputF2'> YES ITS DIV TEXT TO COPY  </div>

<script>

    function myFunctionF2()  {
        str = document.getElementById('myInputF2').innerHTML;
        const el = document.createElement('textarea');
        el.value = str;
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
        alert('Copied the text:' + el.value);
    };
</script>

更多信息:https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f 该文介绍如何使用JavaScript将文本复制到剪贴板。

请解释您的代码是做什么的以及它如何实现;仅提供链接是不够的。 - M-Chen-3
1
请注意,execCommand现在已被弃用 https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand - andrea m.

2
将链接作为答案添加以吸引更多关注Aaron Lavers在第一个答案下的评论。
这非常有效 - http://clipboardjs.com。只需添加clipboard.js或min文件即可。在初始化时,使用包含要单击的html组件的类,并将要复制的内容的组件ID传递给单击元素。

2

以上的解决方案并不适用于可编辑的 div 内容。需要进行更多步骤才能将其内容复制到剪贴板。

以下是如何将 div contenteditable 内容复制到剪贴板的方法。在 iPhone 和 Android 上选择文本并不总是容易的。只需一个复制按钮,即可复制所有内容。

<div id="editor1" contenteditable="true"></div> 

<button id="button1" onclick="CopyToClipboard()">COPY</button>

<script>

function CopyToClipboard() {

    var copyBoxElement = document.getElementById('editor1');
    copyBoxElement.contenteditable = true;
    copyBoxElement.focus();
    document.execCommand('selectAll');
    document.execCommand("copy");
    copyBoxElement.contenteditable = false;
    alert("Text has been copied")
}

</script>

4
请注意,execCommand现已被弃用。https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand - andrea m.

2
对解决方案进行了修改,以便基于类而不是特定的ID在多个div上运行。例如,如果您有多个代码块,则假定div类设置为“code”。
<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>

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