在文本区域中设置文本光标位置 [英] Set text-cursor position in a textarea

查看:68
本文介绍了在文本区域中设置文本光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用BBCode编辑器,这是代码:

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

一切正常,除了一件事是文本光标的位置.当我单击boldText按钮时,它将光标位置设置在Textarea的末尾!

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

推荐答案

使用 txtarea.focus()重新调整文本区域的焦点之后,添加以下行:

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

txtarea.selectionEnd= end + 7;

这会将游标设置为之前的七个位置,这将考虑 [b] [/b] .

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

示例

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>

这篇关于在文本区域中设置文本光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆