8

我听说你不能在不使用 Flash 的情况下复制文本(在浏览器中);那么,有没有办法通过使用锚和 JavaScript 或 jQuery 来选择文本。

<p>Text to be copied</p>

<a>Copy Text Above</a>
4

4 回答 4

28

在较新的浏览器上,您可以执行此操作来选择和复制。这是一个纯 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。

编辑:未来注意事项 - 虽然前面仍然有效,但有人谈到转移到Permissions API并使用Clipboard 接口,看起来像navigator.clipboard.writeText('text')。这个标准还没有最终确定,也没有被许多浏览器支持。随着安全性越来越受到关注,预计未来会出现类似的情况。

于 2015-12-29T02:13:24.787 回答
8

我找到了这个 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!" />

来源

于 2017-12-16T14:19:20.193 回答
4

给定以下示例 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 在 textarea 中选择文本:

$("#selectAll").click(function () {
    $(this).parents(".announcementInfoText").children("textarea").select();
});

现在选择了文本“ This is some sample text that I want to be select to copy to the clipboard ”,您只需按 Ctrl+C 即可将文本复制到剪贴板。

于 2012-10-19T21:17:48.930 回答
3

不运行基于 Flash 的插件的最简单的解决方案是:

$('a').click(function() {
    window.prompt('Press ctrl/cmd+c to copy text', $(this).prev('p').text());
});

http://jsfiddle.net/JFFvG/

于 2012-10-20T20:22:49.743 回答