我听说您在不使用诸如flash之类的东西的情况下无法复制文本(在浏览器中);因此,有没有一种方法可以使用锚和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');
}
此复制命令在所有主要浏览器,Chrome,Firefox(Gecko),Internet Explorer和Opera上都可以使用,不包括Safari。
edit :注意未来 - 虽然前面仍然有效,但仍有关于移至权限API并使用剪贴板接口的讨论,看起来像navigator.clipboard.writeText('text')
。该标准尚未最终确定,也没有得到许多浏览器的支持。随着安全性变得更加关注,将来会期待这样的事情。
我找到了这个jQuery解决方案:
$(function() {
$('input').click(function() {
$(this).focus();
$(this).select();
document.execCommand('copy');
$(this).after("Copied to clipboard");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="copy me!" />
源
给定以下示例html:
<div class="announcementInfoText">
<p class="copyToClipboard">
<a id="selectAll">Select All Text</a>
</p>
<textarea ID="description" class="announcementTextArea">This is some sample text that I want to be select to copy to the clipboard</textarea>
</div>
您可以使用以下jQuery选择文本中的文本:
$("#selectAll").click(function () {
$(this).parents(".announcementInfoText").children("textarea").select();
});
现在,文本" 这是我要选择的一些示例文本。
最简单的解决方案而不运行基于Flash的插件的解决方案就像:
$('a').click(function() {
window.prompt('Press ctrl/cmd+c to copy text', $(this).prev('p').text());
});
http://jsfiddle.net/jffvg/