你如何获得textarea中的光标位置? [英] How do you get the cursor position in a textarea?

查看:983
本文介绍了你如何获得textarea中的光标位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个textarea,我想知道我是在textarea的最后一行还是在textarea的第一行,并且使用了javascript的游标。



我想抓住第一个换行符和最后一个换行符的位置,然后抓住光标的位置。

  var firstNewline = $('#myTextarea')。val()。indexOf('\\\
');
var lastNewline = $('#myTextarea')。val()。lastIndexOf('\\\
');

var cursorPosition = ?????;

if(cursorPosition< firstNewline)
//我在第一行。
else if(cursorPosition> lastNewline)
//我在最后一行。




  • 是否可以抓住textarea中的光标位置?

  • 您是否有更好的建议来了解我是否在textarea的第一行或最后一行?

$ b $



任何帮助都非常值得赞赏。

解决方案

如果没有选择,您可以使用属性 .selectionStart .selectionEnd $ b

  var cursorPosition = $('#myTextarea')。prop( selectionStart); 

请注意,旧版浏览器不支持此功能,最值得注意的是IE8-。在这里你必须使用文本范围,但它是一个完全的挫败感。



我相信有一个库专门用于获取和设置选择/光标位置在输入元素,虽然。我不记得它的名字,但似乎有几十篇关于这个主题的文章。


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.

Any help is much appreciated.

解决方案

If there is no selection, you can use the properties .selectionStart or .selectionEnd (with no selection they're equal).

var cursorPosition = $('#myTextarea').prop("selectionStart");

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.

这篇关于你如何获得textarea中的光标位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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