两者都会像魅力一样工作:),
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 copied")
}}
同样在html中
<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>
<div id="div1" >Text To Copy </div>
<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
这是代码段。
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 copied, copy in the text-area")
}
}
<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>
<div id="div1">Text To Copy </div>
<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
只是为了增加这个答案,有一个简洁的插件我已经使用了几次可以解决这个问题:剪贴板js.com
第一个不工作
请告诉我第一个示例如何工作
我有一个问题,这可以在所有浏览器上使用吗?
我希望它能做到。在Firefox和Chrome中签入。