相关文章推荐
刚失恋的蚂蚁  ·  React ...·  4 月前    · 
爽快的墨镜  ·  能否直接将React ...·  4 月前    · 
满身肌肉的保温杯  ·  ssl medium strength ...·  2 年前    · 
慈祥的黄瓜  ·  数据库home - 知乎·  2 年前    · 
阳光的葫芦  ·  React Hook ...·  2 年前    · 

input 获取光标位置

在 HTML 中,不能直接获取文本框内光标的位置。但是,可以使用 JavaScript 获取光标位置。

如果要获取 input 或 textarea 元素中光标的位置,可以使用 selectionStart 属性。这个属性返回光标所在位置的索引。

const input = document.querySelector('input');
console.log(input.selectionStart);

如果要同时获取光标的起始位置和结束位置,可以使用 selectionStart 和 selectionEnd 属性。

const input = document.querySelector('input');
console.log(input.selectionStart);
console.log(input.selectionEnd);
        lastnigtic
        JavaScript