【问题标题】:Select / Copy Text Using JavaScript or jQuery使用 JavaScript 或 jQuery 选择/复制文本
【发布时间】:2019-11-23 12:24:39
【问题描述】:

我听说不使用 Flash 之类的东西就无法复制文本(在浏览器中);那么,有没有办法通过使用锚点和 JavaScript 或 jQuery 来选择文本。

<p>Text to be copied</p>

<a>Copy Text Above</a>

【问题讨论】:

  • 澄清一下:您是在问如何使用 javascript 将选定的文本复制到剪贴板?
  • 没有。我想要这样,一旦点击了锚点,文本(例如

    中的文本)就会被复制到剪贴板。

  • 也许是 .text() 的东西?

标签: javascript jquery html


【解决方案1】:

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

This copy command works on all major browsers, Chrome, Firefox (Gecko), Internet Explorer, and Opera, excluding Safari.

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

【讨论】:

    【解决方案2】:

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

    Source

    【讨论】:

    • 最后,谢谢。找到一个简单的快速 jquery hack 比你想象的要难得多。我只需要它进行本地测试,因此它不需要是有史以来最强大的代码。
    【解决方案3】:

    给出以下示例 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 selected to be copy to the clipboard”已被选中,您只需按 Ctrl+C 即可将文本复制到剪贴板.

    【讨论】:

      【解决方案4】:

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

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

      http://jsfiddle.net/JFFvG/

      【讨论】:

        猜你喜欢
        • 2012-03-19
        • 2011-04-16
        • 2015-02-19
        • 2013-03-03
        • 1970-01-01
        • 2015-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多