The example in this article describes the method of obtaining and setting the cursor position in Javascript. Share it with everyone for your reference. The details are as follows:
In project development, we often encounter the problem of setting the cursor position to the end of input. Today I checked Google and found out how to get the cursor position (getCursortPosition) and set the cursor position in mainstream browsers such as IE, Firefox, and Opera. (setCursorPosition) function.
1. Get cursor position function:
function getCursortPosition (ctrl) { 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; return (CaretPos); }
2. Set cursor position function:
function setCaretPosition(ctrl, pos){ 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(); } }
I hope this article will be helpful to everyone’s JavaScript programming design.