Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
956 views
in Technique[技术] by (71.8m points)

javascript - Set text-cursor position in a textarea

I'm working on a BBCode editor and here is the code:

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

Everything is OK except one thing which is the position of the text-cursor. When I click on the boldText button, it sets the cursor position at the end of the Textarea!!

Actually, I want to be able to set the cursor position at a certain index. I want something like this:

txtarea.setFocusAt(20);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After refocusing the textarea with txtarea.focus(), add this line:

txtarea.selectionEnd= end + 7;

That will set the cursor seven positions ahead of where it was previously, which will take [b][/b] into account.

Example

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;
}
#editor_area {
  width: 100%;
  height: 10em;
}
<button id="bold">B</button>
<textarea id="editor_area"></textarea>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...