In the project development often encountered input and so set the cursor position to the final question, today I checked Google, found in IE, Firefox, Opera and other mainstream browsers to get the cursor position (getcursortposition) and set the cursor position (setcursorposition) function.
function Getcursortposition (ctrl) {//Get cursor position functions
var caretpos = 0; IE Support
if (document.selection) {
ctrl.focus ();
var Sel = Document.selection.createRange ();
Sel.movestart (' character ',-ctrl.value.length);
Caretpos = Sel.text.length;
}
Firefox Support
else if (Ctrl.selectionstart | | ctrl.selectionstart = = ' 0 ')
caretpos = ctrl.selectionstart;< C11/>return (Caretpos);
}
PS: Parameter ctrl is input or TextArea object
function Setcaretposition (CTRL, POS) {//SET cursor position functions
if (ctrl.setselectionrange)
{
ctrl.focus ();
Ctrl.setselectionrange (Pos,pos);
}
else if (ctrl.createtextrange) {
var range = Ctrl.createtextrange ();
Range.collapse (true);
Range.moveend (' character ', POS);
Range.movestart (' character ', POS);
Range.Select ();
}
PS: Parameter ctrl is input or TextArea object, POS is the location where the cursor is to be moved.