textarea的window.getSelection()不工作在Firefox? [英] window.getSelection() of textarea not working in firefox?
问题描述
我使用下面的代码, window.getSelection()
在textarea接缝不工作在Firefox,
,但在谷歌浏览器工作正常。
- 我使用的是firefox 24,和$ 27。
下面是一个示例:
http://jsfiddle.net/AVLCY/
HTML:
< div> div中的文字< / div>
< textarea> Hello textarea< / textarea>
< div id ='debug'>< / div>
JS:
< $ c $> $(document).on('mouseup','body',function(){
$(#debug)。html(You select'+ getSelectionText()+' );
});
函数getSelectionText(){
if(window.getSelection){
try {
// returnin firefox
return window.getSelection( )的ToString();
catch(e){
console.log('不能获取选择文本')
}
}
//对于IE
if .selection&&& document.selection.type!=Control){
return document.selection.createRange()。text;
$ / code>
解决方案由于 getSelection 对表单字段中选定的文本不起作用=nofollow noreferrer>此Firefox漏洞。
如这个答案,解决方法是使用
selectionStart
和selectionEnd
代替。 b
$ b以下是一个正确的修改示例:
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
andselectionEnd
instead.Here is a modified example that works correctly:
这篇关于textarea的window.getSelection()不工作在Firefox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!