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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20419515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:26:25  来源:igfitidea点击:

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

javascriptfirefox

提问by user3047765

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()textarea 接缝在 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:

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;
    }
}

回答by Falling Plates

It appears getSelectiondoes not work on text selected in form fields due to this Firefox bug.

getSelection由于这个 Firefox 错误,它似乎不适用于在表单字段中选择的文本。

As explained in this answer, the workaround is to use selectionStartand selectionEndinstead.

本答案中所述,解决方法是使用selectionStartandselectionEnd代替。

Here is a modified example that works correctly:

这是一个可以正常工作的修改示例:

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

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