在textarea中设置文本光标位置

shb*_*789 13 javascript textarea

我正在研究BBCode编辑器,这里是代码:

var txtarea = document.getElementById("editor_area");

            function boldText() {
                var start = txtarea.selectionStart;
                var end = txtarea.selectionEnd;
                var sel = txtarea.value.substring(start, end);
                var finText = txtarea.value.substring(0, start) + '[b]' + sel + '[/b]' + txtarea.value.substring(end);
                txtarea.value = finText;
                txtarea.focus();
            }
Run Code Online (Sandbox Code Playgroud)

一切都没问题,除了一个是文本光标的位置.当我点击boldText按钮时,它将光标位置设置在Textarea的末尾!

实际上,我希望能够将光标位置设置为某个索引.我想要这样的东西:

txtarea.setFocusAt(20);
Run Code Online (Sandbox Code Playgroud)

Ric*_*ock 22

重新聚焦textarea后txtarea.focus(),添加以下行:

txtarea.selectionEnd= end + 7;
Run Code Online (Sandbox Code Playgroud)

这将把光标设置在前一个位置之前的七个位置,这将考虑[b][/b]在内.

document.getElementById('bold').addEventListener('click', boldText);

function boldText() {
  var txtarea = document.getElementById("editor_area");
  var start = txtarea.selectionStart;
  var end = txtarea.selectionEnd;
  var sel = txtarea.value.substring(start, end);
  var finText = txtarea.value.substring(0, start) + '[b]' + sel + '[/b]' + txtarea.value.substring(end);
  txtarea.value = finText;
  txtarea.focus();
  txtarea.selectionEnd= end + 7;
}
Run Code Online (Sandbox Code Playgroud)
#editor_area {
  width: 100%;
  height: 10em;
}
Run Code Online (Sandbox Code Playgroud)
<button id="bold">B</button>
<textarea id="editor_area"></textarea>
Run Code Online (Sandbox Code Playgroud)


Mub*_*bas 8

如果你使用jquery,你可以这样做.

$('textarea').prop('selectionEnd', 13);
Run Code Online (Sandbox Code Playgroud)


ash*_*deh 6

您可以使用Jamie Munro ( setSelectionRange()& )编写的以下两个函数setCaretToPos()

function setSelectionRange(input, selectionStart, selectionEnd) {
    if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    }
    else if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    }
}

function setCaretToPos (input, pos) {
       setSelectionRange(input, pos, pos);
}
Run Code Online (Sandbox Code Playgroud)

例子:

例如,如果您想在文本区域的末尾设置插入符号,您可以这样: setCaretToPos(document.getElementById('textarea'), -1);