你如何获得文本区域中的光标位置? [英] How do you get the cursor position in a textarea?
问题描述
我有一个 textarea,我想知道我的光标是在 textarea 的最后一行还是在 textarea 的第一行,并且使用 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('
');
var lastNewline = $('#myTextarea').val().lastIndexOf('
');
var cursorPosition = ?????;
if (cursorPosition < firstNewline)
// I am on first line.
else if (cursorPosition > lastNewline)
// I am on last line.
- 是否可以在 textarea 中抓取光标位置?
- 您是否有更好的建议来确定我是在 textarea 的第一行还是最后一行?
首选 jQuery 解决方案,除非 JavaScript 如此简单或更简单.
jQuery solutions preferred unless JavaScript is as simple or simpler.
推荐答案
如果没有选择,您可以使用属性.selectionStart
或 .selectionEnd
(没有选择他们是平等的).
If there is no selection, you can use the properties .selectionStart
or .selectionEnd
(with no selection they're equal).
var cursorPosition = $('#myTextarea').prop("selectionStart");
请注意,较旧的浏览器不支持此功能,尤其是 IE8-.在那里您必须处理文本范围,但这完全令人沮丧.
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.
这篇关于你如何获得文本区域中的光标位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!