Set textarea selection in Internet Explorer

前端 未结 4 688
灰色年华
灰色年华 2020-12-05 15:23

I\'m looking for a way to set a selection in a textarea in Internet Explorer. In other browsers, this works just fine:

textarea.selectionStart = sta         


        
相关标签:
4条回答
  • 2020-12-05 15:48

    Beware of line separators, move* methods see them as one character, but they are actually two - \r\n

    0 讨论(0)
  • 2020-12-05 15:58

    Try with

    function select(e, start, end){
         e.focus();
         if(e.setSelectionRange)
            e.setSelectionRange(start, end);
         else if(e.createTextRange) {
            e = e.createTextRange();
            e.collapse(true);
            e.moveEnd('character', end);
            e.moveStart('character', start);
            e.select();
         }
    }
    select(document.getElementById('textarea_id'), 5, 10);
    
    0 讨论(0)
  • 2020-12-05 16:05

    This works for me:

    <textarea id="lol">
    noasdfkvbsdobfbgvobosdobfbgoasopdobfgbooaodfgh
    </textarea>
    
    <script>
    var range = document.getElementById('lol').createTextRange();
    range.collapse(true);
    range.moveStart('character', 5);
    range.moveEnd('character', 10);
    range.select();
    </script>
    

    Useful links:

    • http://help.dottoro.com/ljlwflaq.php
    • http://www.webreference.com/programming/javascript/ncz/
    • http://www.quirksmode.org/dom/range_intro.html

    moveStart() at MSDN: http://msdn.microsoft.com/en-us/library/ms536623%28VS.85%29.aspx

    moveEnd() at MSDN: http://msdn.microsoft.com/en-us/library/ms536620%28VS.85%29.aspx

    0 讨论(0)
  • 2020-12-05 16:05

    As already commented the move methods see the line separators as one character (\n) instead of two (\r\n). I have adjusted the routine to compensate for that:

    function select(el, start, end) {
        el.focus();
    
        if (el.setSelectionRange) { 
            el.setSelectionRange(start, end);
        } 
        else { 
            if(el.createTextRange) { 
                var normalizedValue = el.value.replace(/\r\n/g, "\n");
    
                start -= normalizedValue.slice(0, start).split("\n").length - 1;
                end -= normalizedValue.slice(0, end).split("\n").length - 1;
    
                range=el.createTextRange(); 
                range.collapse(true);
                range.moveEnd('character', end);
                range.moveStart('character', start); 
                range.select();
            } 
        }
    }
    
    0 讨论(0)
提交回复
热议问题