textarea 的 window.getSelection() 在 Firefox 中不起作用? [英] window.getSelection() of textarea not working in firefox?
问题描述
我正在尝试在 HTML 页面上获取选择文本.
我使用下面的代码,并且 window.getSelection()
在 textarea 接缝上在 firefox 中不起作用,但在 Google Chrome 中运行良好.
- 我使用的是 Firefox 24 和 chrome 27.
这是一个示例:http://jsfiddle.net/AVLCY/
HTML:
div中的文本<textarea>你好 textarea</textarea><div id='调试'></div>
JS:
$(document).on('mouseup','body',function(){$("#debug").html("你选择'" + getSelectionText() + "'");});函数 getSelectionText() {如果(window.getSelection){尝试 {//在 Firefox 中返回 ""返回 window.getSelection().toString();}赶上(e){console.log('无法获取选择文本')}}//对于 IEif (document.selection && document.selection.type != "Control") {返回 document.selection.createRange().text;}}
由于 这个 Firefox 错误.
如此答案中所述,解决方法是使用 selectionStart
和 selectionEnd
代替.
这是一个可以正常工作的修改示例:
I am trying to get selection text on HTML page.
I use below code, and window.getSelection()
on textarea seams not work in firefox,
but works fine in Google Chrome.
- I am using firefox 24, and chrome 27.
Here is a sample: 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;
}
}
It appears getSelection
does not work on text selected in form fields due to this Firefox bug.
As explained in this answer, the workaround is to use selectionStart
and selectionEnd
instead.
Here is a modified example that works correctly:
这篇关于textarea 的 window.getSelection() 在 Firefox 中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!