Как я могу получить позицию курсора из поля ввода?
Я нашел несколько остатков через Google, но ничто пуленепробиваемое.
В основном что-то как плагин jQuery было бы идеально, таким образом, я мог просто сделать
$("#myinput").caretPosition()
Более простое обновление:
Используйте field.selectionStart
пример в этом ответе
Спасибо @commonSenseCode за указание на это.
Старый ответ:
Нашел это решение. Не jquery-based, но интегрировать его в 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;
}
Отличный вариант, большое спасибо Максу.
Я обернул функциональность в его ответе в 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);