使用JavaScript或jQuery选择/复制文本

use*_*756 7 html javascript jquery

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

<p>Text to be copied</p>

<a>Copy Text Above</a>
Run Code Online (Sandbox Code Playgroud)

Zam*_*col 21

在较新的浏览器上,您可以执行此操作以进行选择和复制.这是一个纯粹的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');
}
Run Code Online (Sandbox Code Playgroud)

此复制命令适用于所有主要浏览器,Chrome,Firefox(Gecko),Internet Explorer和Opera,不包括Safari.


Dig*_*art 7

我找到了这个 jQuery 解决方案:

$(function() {
 $('input').click(function() {
 $(this).focus();
 $(this).select();
 document.execCommand('copy');
 $(this).after("Copied to clipboard");
 });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="copy me!" />
Run Code Online (Sandbox Code Playgroud)

来源


Cra*_*per 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>
Run Code Online (Sandbox Code Playgroud)

您可以使用以下 jQuery 选择文本区域中的文本:

$("#selectAll").click(function () {
    $(this).parents(".announcementInfoText").children("textarea").select();
});
Run Code Online (Sandbox Code Playgroud)

既然选择了文本“这是我想要选择复制到剪贴板的一些示例文本”,您只需按 Ctrl+C 即可将文本复制到剪贴板。