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

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

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

如何复制这个 div 中的文本?

<div id="div1">Text To Copy</div>
160642 次浏览

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

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

    <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)

Update March 27th, 2019.

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).

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

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.

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

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

I was getting selectNode() param 1 is not of 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>

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?

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".

<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>
<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>

more info: https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f

The solutions above do not work for the content editable div. A few more steps are needed to copy its content to the clipboard.

Here is how to copy div contenteditable to the clipboard. Selecting text on the iphone and Android is not always easy. With one Copy button you can copy all the content.

<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>

Here you can see code which works on different browsers, including 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>