javascript textarea 的 window.getSelection() 在 Firefox 中不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20419515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
window.getSelection() of textarea not working in firefox?
提问by user3047765
I am trying to get selection text on HTML page.
我正在尝试在 HTML 页面上获取选择文本。
I use below code, and window.getSelection()
on textarea seams not work in firefox,
but works fine in Google Chrome.
我使用下面的代码,并且window.getSelection()
textarea 接缝在 firefox 中不起作用,但在谷歌浏览器中工作正常。
- I am using firefox 24, and chrome 27.
- 我正在使用 Firefox 24 和 chrome 27。
Here is a sample: http://jsfiddle.net/AVLCY/
这是一个示例:http: //jsfiddle.net/AVLCY/
HTML:
HTML:
<div>Text in div</div>
<textarea>Hello textarea</textarea>
<div id='debug'></div>
JS:
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;
}
}
回答by Falling Plates
It appears getSelection
does not work on text selected in form fields due to this Firefox bug.
getSelection
由于这个 Firefox 错误,它似乎不适用于在表单字段中选择的文本。
As explained in this answer, the workaround is to use selectionStart
and selectionEnd
instead.
如本答案中所述,解决方法是使用selectionStart
andselectionEnd
代替。
Here is a modified example that works correctly:
这是一个可以正常工作的修改示例: