如何从输入字段中获取插入符号的位置?
我已经通过谷歌找到了一些零碎的东西,但没有任何防弹的东西。
基本上,像jQuery插件这样的东西是理想的,所以我可以简单地做
$("#myinput").caretPosition()
发布于 2018-01-08 21:02:26
使用selectionStart
。它是compatible with all major browsers。
document.getElementById('foobar').addEventListener('keyup', e => {
console.log('Caret at: ', e.target.selectionStart)
})
<input id="foobar" />
仅当输入上未定义类型或未定义type="text"
或type="textarea"
时,此方法才有效。
发布于 2010-05-24 21:59:51
我已经将bezmax's answer中的功能封装到jQuery中,如果有人想使用它的话。
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
return sel.text.length - selLen;
}
}
})(jQuery);
发布于 2014-01-29 18:28:41
现在有一个很好的插件来解决这个问题:The Caret Plugin
然后,您可以使用$("#myTextBox").caret()
或通过$("#myTextBox").caret(position)
设置位置
https://stackoverflow.com/questions/2897155
复制相似问题