繁体   English   中英

通过element.select()选择文本时,document.getSelection()。toString()返回空字符串

[英]document.getSelection().toString() returns empty string when the text is selected via element.select()

我正在尝试实现以下两个功能:

  1. 用户可以通过单击按钮在textarea复制内容。
  2. 通过侦听copy事件,我可以知道用户复制了哪些内容(用户是否使用按钮,Ctrl-C或上下文菜单进行copy

这是我的代码(您也可以在https://jsfiddle.net/hjtswedm/3/中看到它):

<html>

<head>
</head>
<script src='https://code.jquery.com/jquery-2.2.4.min.js'></script>
<script>
    $(window).bind("copy", function (e) {
        alert(document.getSelection().toString());
    });

    var copyText = function () {
        var txt = document.createElement("textarea");
        txt.textContent = $('#data').val();
        txt.style.position = "fixed";
        document.body.appendChild(txt);
        txt.select();
        try {
            return document.execCommand("copy");
        } catch (ex) {
            return false;
        } finally {
            document.body.removeChild(txt);
        }
    }
</script>

<body>
    Lorem Ipsum
    <textarea id="data">test copy</textarea>
    <button onclick="copyText()">
    Copy Text
    </button>
</body>

</html>

这段代码可以在Chrome上正常运行。 但是,对于Firefox,Internet Explorer和Edge,当我单击复制按钮时, document.getSelection().toString()始终返回空字符串。 这是设计使然,还是我想念什么?

提前致谢。

工作提琴

尝试:

 try {
    var range = document.createRange();
    range.selectNodeContents(txt);
    window.getSelection().addRange(range);
    return document.execCommand("copy");
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM