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

Javascript method to obtain and set cursor position_javascript skills

WBOY
Release: 2016-05-16 15:49:39
Original
2064 people have browsed it

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);
}

Copy after login

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();
  }
}

Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template