Specifying Where To Focus Within Textarea

后端 未结 2 830
日久生厌
日久生厌 2020-12-18 14:32

I have a textarea...


What I want to do is focus the u

相关标签:
2条回答
  • 2020-12-18 14:48

    Use the following function to set a selection within a textarea.

    function setSelRange(inputEl, selStart, selEnd) { 
       if (inputEl.setSelectionRange) { 
         inputEl.focus(); 
         inputEl.setSelectionRange(selStart, selEnd); 
       } else if (inputEl.createTextRange) { 
         var range = inputEl.createTextRange(); 
         range.collapse(true); 
         range.moveEnd('character', selEnd); 
         range.moveStart('character', selStart); 
         range.select(); 
       } 
    }
    // From http://www.webmasterworld.com/forum91/4527.htm
    

    So, in your case, you can search for the position of the * character and use that value in a call like this:

    var pos = 17; // Set this to the position of the * character.
    setSelRange(document.getElementById('textareaId'), pos, pos);
    
    0 讨论(0)
  • 2020-12-18 14:58

    just to make your burden lighter.

    <textarea id="myarea">
    Some writing here
    *
    Then some more on another line
    </textarea>
    
    
    function FocusMe(what){ // what = character to be focused(in your case *)
     var cFocus = document.getElemenById("myarea").innerHTML;
     var pos = cFocus.indexOf(what);
     setSelRange(document.getElementById('myarea'), pos, pos); //Jame's answer above.
    }
    
    0 讨论(0)
提交回复
热议问题