textarea的window.getSelection()不工作在Firefox? [英] window.getSelection() of textarea not working in firefox?

查看:137
本文介绍了textarea的window.getSelection()不工作在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

    以下是一个正确的修改示例:

    http://jsfiddle.net/AVLCY/1/


    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:

    http://jsfiddle.net/AVLCY/1/

    这篇关于textarea的window.getSelection()不工作在Firefox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆