Specifying Where To Focus Within Textarea

巧了我就是萌 提交于 2019-12-18 05:18:12

问题


I have a textarea...

<textarea>
Some writing here
*
Then some more on another line
</textarea>

What I want to do is focus the user where the * is. Is this possible?


回答1:


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);



回答2:


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.
}


来源:https://stackoverflow.com/questions/1552567/specifying-where-to-focus-within-textarea

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!