问题
When I highlight numbers on an <input type="number">
in Chrome, window.getSelection().toString()
successfully gives me the highlighted text.
But this is not so in Firefox; it is always blank. Does anyone know why? This is really confusing since MDN getSelection documentation states it should work in Firefox 57.
回答1:
This is a firefox bug. See https://bugzilla.mozilla.org/show_bug.cgi?id=85686
Very old one, not fixed yet.
I use the following code as workaround:
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;
}
}
来源:https://stackoverflow.com/questions/47517432/window-getselection-tostring-not-working-in-firefox-works-in-chrome