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?
  • 你有更好的建议来确定我是在文本区的第一行还是最后一行吗?

jQuery solutions preferred unless JavaScript is as simple or simpler.

推荐答案

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.

Jquery相关问答推荐

将div中的下一个2个标题分组

ASP.NET Core 8 MVC:从jQuery发布控制器中的所有值为空

使用jquery ui来回滑动切换

添加动态表单后,Select2 消失

jQuery .append() 创建两个元素而不是一个

如何从 onclick div 属性检测 Javascript 中的 control+click?

jQuery:使用变量作为 Select 器

如何使用 jQuery 获取所有 ID?

jquery清除输入默认值

显示的 jQuery 日期 Select 器年份

jQuery获取表单字段值

jQuery - 使用发布数据重定向

如果 iframe src 无法加载,则捕获错误.错误:-拒绝在框架中显示 'http://www.google.co.in/'..

使用 JQuery / JavaScript 调用/单击 mailto 链接

使用 jQuery 拖放防止单击事件

如何将数组传递给 jQuery .data() 属性

jQuery - 确定输入元素是文本框还是 Select 列表

如何从所有元素jquery中删除类

设置 JQuery event.preventDefault() 时绕过 window.open 上的弹出窗口阻止程序

页面加载后如何执行jquery代码?