好的 :) 我有一个id为#toCopy的div,以及一个id为#copy的按钮。 当按下#copy按钮时,复制#toCopy内容到剪贴板的最佳方法是什么?
好的 :) 我有一个id为#toCopy的div,以及一个id为#copy的按钮。 当按下#copy按钮时,复制#toCopy内容到剪贴板的最佳方法是什么?
在几乎任何浏览器上,你都可以从只有 input 元素(即具有 .value
属性的元素)中复制到剪贴板,但是无法从像 <div>
、<p>
、<span>
这样的元素(即具有 .innerHTML
属性的元素)中复制。
不过我使用以下技巧实现了这一点:
<textarea>
<div>
的 innerHTML
复制到新创建的 <textarea>
中<textarea>
的 .value
复制到剪贴板<textarea>
元素function CopyToClipboard (containerid) {
// Create a new textarea element and give it id='temp_element'
const textarea = document.createElement('textarea')
textarea.id = 'temp_element'
// Optional step to make less noise on the page, if any!
textarea.style.height = 0
// Now append it to your page somewhere, I chose <body>
document.body.appendChild(textarea)
// Give our textarea a value of whatever inside the div of id=containerid
textarea.value = document.getElementById(containerid).innerText
// Now copy whatever inside the textarea to clipboard
const selector = document.querySelector('#temp_element')
selector.select()
document.execCommand('copy')
// Remove the textarea
document.body.removeChild(textarea)
}
<div id="to-copy">
This text will be copied to your clipboard when you click the button!
</div>
<button onClick="CopyToClipboard('to-copy')">Copy</button>
没有id的相同:
function copyClipboard(el, win){
var textarea,
parent;
if(!win || (win !== win.self) || (win !== win.window))
win = window;
textarea = document.createElement('textarea');
textarea.style.height = 0;
if(el.parentElement)
parent = el.parentElement;
else
parent = win.document;
parent.appendChild(textarea);
textarea.value = el.innerText;
textarea.select();
win.document.execCommand('copy');
parent.removeChild(textarea);
}
不过我没有测试过不同的窗口(iframes
)!
更新的答案 早期JavaScript受到了剪贴板的限制, 但现在它支持复制/粘贴命令。 请参阅Mozilla和caniuse.com的文档。
document.execCommand('paste')
https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand http://caniuse.com/#search=command
Javascript不允许使用剪贴板,但其他插件如flash可以访问。