【问题标题】:document.getSelection().toString() returns empty string when the text is selected via element.select()document.getSelection().toString() 通过 element.select() 选择文本时返回空字符串
【发布时间】:2017-06-01 12:01:21
【问题描述】:

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

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

这是我的代码(你也可以在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() 总是返回空字符串。这是设计使然,还是我错过了什么?

提前致谢。

【问题讨论】:

标签: javascript jquery


【解决方案1】:

Working fiddle

试试:

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

【讨论】:

  • 感谢您的回答。你的小提琴对我也很有效,但如果我将代码保存到 HTML 文件并在 Microsoft Edge 中打开它(仍然为空 document.getSelection().toString()),则代码不起作用。你能帮忙再检查一下吗?谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多