我有一个textarea ...
<textarea>
Some writing here
*
Then some more on another line
</textarea>
我想要做的是将用户聚焦在*所在的位置。这可能吗?
答案 0 :(得分:5)
使用以下功能在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
因此,在您的情况下,您可以搜索*
字符的位置,并在这样的调用中使用该值:
var pos = 17; // Set this to the position of the * character.
setSelRange(document.getElementById('textareaId'), pos, pos);
答案 1 :(得分:0)
只是为了减轻你的负担。
<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.
}