Get cursor position (in characters) within a text

2018-12-31 04:19发布

How can I get the caret position from within an input field?

I have found a few bits and pieces via Google, but nothing bullet proof.

Basically something like a jQuery plugin would be ideal, so I could simply do

$("#myinput").caretPosition()

8条回答
人间绝色
2楼-- · 2018-12-31 05:09

VERY EASY

Updated answer

Use selectionStart, it is compatible with all major browsers.

document.getElementById('foobar').addEventListener('keyup', e => {
  console.log('Caret at: ', e.target.selectionStart)
})
<input id="foobar" />

Update: This works only when no type is defined or type="text" on the input.

查看更多
只若初见
3楼-- · 2018-12-31 05:11

There are a few good answers posted here, but I think you can simplify your code and skip the check for inputElement.selectionStart support: it is not supported only on IE8 and earlier (see documentation) which represents less than 1% of the current browser usage.

var input = document.getElementById('myinput'); // or $('#myinput')[0]
var caretPos = input.selectionStart;

// and if you want to know if there is a selection or not inside your input:

if (input.selectionStart != input.selectionEnd)
{
    var selectionValue =
    input.value.substring(input.selectionStart, input.selectionEnd);
}
查看更多
登录 后发表回答