简体   繁体   English

textarea 的 window.getSelection() 在 firefox 中不起作用?

[英]window.getSelection() of textarea not working in firefox?

I am trying to get selection text on HTML page.我正在尝试在 HTML 页面上获取选择文本。

I use below code, and window.getSelection() on textarea seams not work in firefox, but works fine in Google Chrome.我使用下面的代码,文本区域接缝上的window.getSelection()在 firefox 中不起作用,但在谷歌浏览器中工作正常。

  • I am using firefox 24, and chrome 27.我正在使用 firefox 24 和 chrome 27。

Here is a sample: http://jsfiddle.net/AVLCY/这是一个示例: http://jsfiddle.net/AVLCY/

HTML: HTML:

<div>Text in div</div>
<textarea>Hello textarea</textarea>
<div id='debug'></div>

JS:记者:

$(document).on('mouseup','body',function(){
   $("#debug").html("You select '" + getSelectionText() + "'");
});

function getSelectionText() {
    if (window.getSelection) {
        try {
            // return "" in firefox
            return window.getSelection().toString();
        } catch (e) {
            console.log('Cant get selection text')
        }
    } 
    // For IE
    if (document.selection && document.selection.type != "Control") {
        return document.selection.createRange().text;
    }
}

It appears getSelection does not work on text selected in form fields due to this Firefox bug . 由于此Firefox错误 ,似乎getSelection对表单字段中选择的文本无效。

As explained in this answer , the workaround is to use selectionStart and selectionEnd instead. 本回答所述,解决方法是使用selectionStartselectionEnd

Here is a modified example that works correctly: 这是一个正常工作的修改示例:

http://jsfiddle.net/AVLCY/1/ http://jsfiddle.net/AVLCY/1/

It's late 2022 and Firefox still has this weird bug.现在是 2022 年末,Firefox 仍然有这个奇怪的错误。 I went to the original Bug Report on BugZilla to get more info about this and found a workaround (kindly shared by user daniel.lee1ibm ):我查看了 BugZilla 上的原始错误报告以获取更多相关信息并找到了解决方法(由用户daniel.lee1ibm 友情分享):

    //Workaround for Firefox bug 
    const selectedText = document.activeElement.value.substring(
        document.activeElement.selectionStart,
        document.activeElement.selectionEnd
      )

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

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