【问题标题】:window.getSelection() of textarea not working in firefox?textarea的window.getSelection()在Firefox中不起作用?
【发布时间】:2013-12-23 13:05:34
【问题描述】:

我正在尝试在 HTML 页面上获取选择文本。

我使用下面的代码,而 window.getSelection() 的 textarea 接缝在 Firefox 中不起作用, 但在 Google Chrome 中运行良好。

  • 我使用的是 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;
    }
}

【问题讨论】:

标签: javascript firefox


【解决方案1】:

由于this Firefox buggetSelection 似乎不适用于在表单字段中选择的文本。

this answer 中所述,解决方法是改用selectionStartselectionEnd

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

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

【讨论】:

  • 这个问题还有其他解决方案吗?
  • 我将“textarea”更改为“:focus”,所以如果有多个 textarea 或输入字段,它可以工作:jsfiddle.net/AVLCY/653
猜你喜欢
  • 1970-01-01
  • 2012-12-26
  • 2017-09-26
  • 1970-01-01
  • 2019-11-13
  • 1970-01-01
  • 1970-01-01
  • 2012-05-22
  • 1970-01-01
相关资源
最近更新 更多