Home  >  Article  >  Web Front-end  >  Javascript method to obtain and set cursor position_javascript skills

Javascript method to obtain and set cursor position_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:49:392003browse

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn