window.getSelection()的textarea无法在firefox中运行?

use*_*765 12 javascript firefox

我想在HTML页面上获取选择文本.

我使用下面的代码,并window.getSelection()在textarea接缝不能在Firefox中工作,但在谷歌浏览器中工作正常.

  • 我使用的是firefox 24和chrome 27.

这是一个示例:http: //jsfiddle.net/AVLCY/

HTML:

<div>Text in div</div>
<textarea>Hello textarea</textarea>
<div id='debug'></div>
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Fal*_*tes 13

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

本回答所述,解决方法是使用selectionStartselectionEnd不是.

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

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