更新更容易:
使用时
selectionStart,它与所有主要浏览器兼容。
document.getElementById('foobar').addEventListener('keyup', e => { console.log('Caret at: ', e.target.selectionStart)})<input id="foobar" />
更新:仅当未定义类型或
type="text"在输入上时,此方法才有效。
旧答案:
找到了这个解决方案。不是基于jquery的,但是将其集成到jquery中没有问题:
function doGetCaretPosition (oField) { // Initialize var iCaretPos = 0; // IE Support if (document.selection) { // Set focus on the element oField.focus(); // To get cursor position, get empty selection range var oSel = document.selection.createRange(); // Move selection start to 0 position oSel.moveStart('character', -oField.value.length); // The caret position is selection length iCaretPos = oSel.text.length; } // Firefox support else if (oField.selectionStart || oField.selectionStart == '0') iCaretPos = oField.selectionDirection=='backward' ? oField.selectionStart : oField.selectionEnd; // Return results return iCaretPos;}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)