问题 window.getSelection()的textarea无法在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>

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

6195
2017-12-06 08:41


起源

参考: stackoverflow.com/questions/717224/... - Parkash Kumar
这是由于 Firefox bug于2001年提交 (是的,14年前)。 - Dan Dascalescu


答案:


它出现 getSelection 因为表单字段中选择的文本不起作用 这个Firefox的bug

如中所述 这个答案,解决方法是使用 selectionStart 和 selectionEnd 代替。

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

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


11
2017-12-06 15:35



这个问题还有其他解决办法吗? - Rajesh Choudhary
我将“textarea”更改为“:focus”,因此如果有多个textarea或输入字段,它会起作用: jsfiddle.net/AVLCY/653 - Thibault