Easier update:
(更新更容易:)
Use field.selectionStart
example in this answer .
(在此答案中使用field.selectionStart
示例 。)
Thanks to @commonSenseCode for pointing this out.
(感谢@commonSenseCode指出这一点。)
Old answer:
(旧答案:)
Found this solution.
(找到了这个解决方案。)
Not jquery based but there is no problem to integrate it to jquery:(不是基于jquery的,但是将其集成到jquery中没有问题:)
/*
** Returns the caret (cursor) position of the specified text field (oField).
** Return value range is 0-oField.value.length.
*/
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;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…