如何将光标转移到文本中心中当前活动线的末端?
我们有一个textarea
,并希望将光标设置为当前活动线的末尾在光标所在的位置。
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函数后的单词光标
之后结束。
JavaScript代码将是什么?
一些初始想法:
要使用该代码的行编号:
let line_number = textarea.value.substr(0, textarea.selectionStart).split("\n").length;
要跨越文本的所有行:
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;
似乎不起作用...
我们必须计算所有字符直到当前线,然后将线长度添加到它 - 这是新的光标位置?
We have a textarea
and want to set the cursor to the end of the currently active line where the cursor is situated.
Example content within the textarea:
This is our first line,
then comes a second line,
followed by a third line which holds *|* the cursor
and a fourth line.
Now the blinking cursor *|*
should end up after the word cursor
after execution of the javascript function.
What would be the javascript code to do this?
Some initial Ideas:
To get the line number this code can be used:
let line_number = textarea.value.substr(0, textarea.selectionStart).split("\n").length;
To go over all lines of the textarea:
let lines = textarea.value.split("\n");
Get length of current line:
let end_of_line = lines[line_number-1].length;
Then:
// set the cursor position to the end of the line
textarea.selectionStart = end_of_line;
Seems not to work...
Do we have to count all chars until the current line and then add the line length to it - this as the new cursor position?!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是我想到的解决方案:
不保证它是100%正确并且在所有情况下都起作用。
This is the solution I came up with:
No guarantee that it is 100 % correct and works in all cases.