The problem is with spaces. Sometimes if the caret is on a space, it ignores the space and finds the position of the last character (that isn't a space). In this demo if you click just right of the letter c it shows caret position as 3. Then click just left of the letter d (one character along) and it still shows caret position as 3. However if you click left of d first, then it shows position 4 (the correct position). If anyone can take a look at my jsFiddle and try this out maybe you can find a solution. Thank you.
NB this code only works in IE.
$('input').click(function(){
var Sel = document.selection.createRange();
Sel.moveStart('character', -this.value.length);
CaretPos = Sel.text.length;
$('span').text(CaretPos);
});
The selectionStart
worked in latest IE, Firefox & Chrome.
$('input').click(function(){
this.focus();
/**var Sel = document.selection.createRange();
Sel.moveStart('character', -inelem.value.length);
CaretPos = Sel.text.length;*/
CaretPos = this.selectionStart;
$('span').text(CaretPos);
});
But, if you are concerned about supporting older IE versions, you can conditionally invoke createRange
over selectionStart
. Check this version of fiddle. The doGetCaretPosition
is based on this link
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.