window.getSelection().toString()在Firefox中不起作用(在Chrome中有效) [英] window.getSelection().toString() not working in Firefox (works in Chrome)
问题描述
当我在Chrome中的<input type="number">
上突出显示数字时,window.getSelection().toString()
成功为我提供了突出显示的文本.
When I highlight numbers on an <input type="number">
in Chrome, window.getSelection().toString()
successfully gives me the highlighted text.
但是Firefox并非如此;它总是空白.有人知道为什么吗?由于 MDN getSelection文档指出了这一点,这确实令人困惑应该可以在Firefox 57中使用.
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.
推荐答案
这是一个firefox错误.请参见 https://bugzilla.mozilla.org/show_bug.cgi?id=85686
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;
}
}
这篇关于window.getSelection().toString()在Firefox中不起作用(在Chrome中有效)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!