如何将光标移动到文本区域内当前活动行的末尾?



我们有一个textarea,并希望将光标设置到当前活动行的末尾光标所在位置

文本区域内的示例内容:

This is our first line,
then comes a second line,
followed by a third line which holds *|* the cursor
and a fourth line.

现在,闪烁的光标*|*应该在执行javascript函数后的cursor之后结束。

是什么javascript代码来做到这一点?


一些初步的想法:

要获取行号,可以使用以下代码:

let line_number = textarea.value.substr(0, textarea.selectionStart).split("n").length;

查看textarea的所有行:

let lines = textarea.value.split("n");

获取当前行长度:

let end_of_line = lines[line_number-1].length;

:

// set the cursor position to the end of the line
textarea.selectionStart = end_of_line;

似乎不工作…

我们是否必须计算所有字符直到当前行,然后添加行长度-这是新的光标位置?!

这是我想到的解决方案:

// line where cursor is now
let line_number = textarea.value.substr(0, textarea.selectionStart).split("n").length;
// split all lines of the textarea
let contentlines = textarea.value.split("n");
let charcount = 0;
for (var i=0; i < line_number-1; i++)
{
// count line break as one char
charcount += contentlines[i].length + 1;
}
let end_of_line = contentlines[line_number-1].length;
textarea.selectionStart = charcount+end_of_line;
textarea.selectionEnd = charcount+end_of_line;

不保证它在所有情况下都是100%正确的。

最新更新