window.getSelection()。toString()无法在Firefox中运行(适用于Chrome)

时间:2017-11-27 18:22:02

标签: javascript firefox mozilla

当我在Chrome中的window.getSelection().toString()上突出显示数字时,.AllowMultiSelect = False成功地为我提供了突出显示的文字。

但在Firefox中并非如此;它总是空白的。有谁知道为什么?这真是令人困惑,因为MDN getSelection documentation表明它应该在Firefox 57中起作用。

1 个答案:

答案 0 :(得分:0)

这是一个Firefox错误。参见https://bugzilla.mozilla.org/show_bug.cgi?id=85686

一个很老的,还没有修复。

我使用以下代码作为解决方法:

        function getSelectionText() {
            if (window.getSelection) {
                try {
                    var activeElement = document.activeElement;
                    if (activeElement && activeElement.value) {
                        // firefox bug https://bugzilla.mozilla.org/show_bug.cgi?id=85686
                        return activeElement.value.substring(activeElement.selectionStart, activeElement.selectionEnd);
                    } else {
                        return window.getSelection().toString();
                    }

                } catch (e) {
                }
            } else if (document.selection && document.selection.type != "Control") {
                // For IE
                return document.selection.createRange().text;
            }
        }        
相关问题