我听说不使用 Flash 之类的东西就不能(在浏览器中)复制文本;那么,有没有一种方法可以使用 anchor 和 JavaScript 或 jQuery 来选择文本。
<p>Text to be copied</p>
<a>Copy Text Above</a>
最佳答案
在较新的浏览器上,您可以执行此操作来选择和复制。这是一个纯 Javascript 解决方案。
function copy_text(element) {
//Before we copy, we are going to select the text.
var text = document.getElementById(element);
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
//add to clipboard.
document.execCommand('copy');
}
编辑: future 注意事项 -
虽然前面的仍然有效,但有关于移动到 Permissions API 的讨论。并使用 Clipboard interface ,看起来像 navigator.clipboard.writeText('text')
。该标准尚未最终确定,也未被许多浏览器支持。随着安全性越来越受到关注,期待 future 出现这样的事情。
关于javascript - 使用 JavaScript 或 jQuery 选择/复制文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12982156/