如何获取文本区域中的光标位置?
我有一个文本区域,我想知道我的 JavaScript 光标位于文本区域的最后一行还是文本区域的第一行。
我想到了抓取第一个换行符和最后一个换行符的位置,然后抓取光标的位置。
var firstNewline = $('#myTextarea').val().indexOf('\n');
var lastNewline = $('#myTextarea').val().lastIndexOf('\n');
var cursorPosition = ?????;
if (cursorPosition < firstNewline)
// I am on first line.
else if (cursorPosition > lastNewline)
// I am on last line.
- 是否可以抓取文本区域内的光标位置?
- 您有更好的建议来确定我是在文本区域的第一行还是最后一行吗?
首选 jQuery 解决方案,除非 JavaScript 也同样简单或更简单。
I have a textarea and I would like to know if I am on the last line in the textarea or the first line in the textarea with my cursor with JavaScript.
I thought of grabbing the position of the first newline character and the last newline character and then grabbing the position of the cursor.
var firstNewline = $('#myTextarea').val().indexOf('\n');
var lastNewline = $('#myTextarea').val().lastIndexOf('\n');
var cursorPosition = ?????;
if (cursorPosition < firstNewline)
// I am on first line.
else if (cursorPosition > lastNewline)
// I am on last line.
- Is it possible to grab the cursor position within the textarea?
- Do you have a better suggestion for finding out if I am on the first or last line of a textarea?
jQuery solutions preferred unless JavaScript is as simple or simpler.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果没有选择,您可以使用属性
.selectionStart
或.selectionEnd
(没有选择它们是相等的)。请注意,旧版浏览器不支持此功能,尤其是 IE8-。在那里你必须处理文本范围,但这完全令人沮丧。
不过,我相信有一个库专门用于获取和设置输入元素中的选择/光标位置。我不记得它的名字了,但似乎有几十篇关于这个主题的文章。
If there is no selection, you can use the properties
.selectionStart
or.selectionEnd
(with no selection they're equal).Note that this is not supported in older browsers, most notably IE8-. There you'll have to work with text ranges, but it's a complete frustration.
I believe there is a library somewhere which is dedicated to getting and setting selections/cursor positions in input elements, though. I can't recall its name, but there seem to be dozens on articles about this subject.
这是我的标准库中的跨浏览器函数:
在代码中使用它,如下所示:
这是它的补充函数:
http://jsfiddle。网/gilly3/6SUN8/
Here's a cross browser function I have in my standard library:
Use it in your code like this:
Here's its complementary function:
http://jsfiddle.net/gilly3/6SUN8/
这是获取行号和列位置的代码
tArea 是文本区域 DOM 元素
Here is code to get line number and column position
tArea is the text area DOM element