Js Code example for obtaining the cursor position and setting the cursor position in the text box

Source: Internet
Author: User

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function getTxt1CursorPosition (){
Var oTxt1 = document. getElementById ("txt1 ");
Var cursurPosition =-1;
If (oTxt1.selectionStart) {// non-IE browser
CursurPosition = oTxt1.selectionStart;
} Else {// IE
Var range = document. selection. createRange ();
Range. moveStart ("character",-oTxt1.value. length );
CursurPosition = range. text. length;
}
Alert (cursurPosition );
}

Function setTxt1CursorPosition (I ){
Var oTxt1 = document. getElementById ("txt2 ");
Var cursurPosition =-1;
If (oTxt1.selectionStart) {// non-IE browser
OTxt1.selectionStart = I;
} Else {// IE
Var range = oTxt1.createTextRange ();
Range. move ("character", I );
Range. select ();
}
}

Function getTa1CursorPosition (){
Var evt = window. event? Window. event: getTa1CursorPosition. caller. arguments [0];
Var oTa1 = document. getElementById ("ta1 ");
Var cursurPosition =-1;
If (oTa1.selectionStart) {// non-IE browser
CursurPosition = oTa1.selectionStart;
} Else {// IE
Var range = oTa1.createTextRange ();
Range. moveToPoint (evt. x, evt. y );
Range. moveStart ("character",-oTa1.value. length );
CursurPosition = range. text. length;
}
Alert (cursurPosition );
}

Function setTa1CursorPosition (I ){
Var oTa2 = document. getElementById ("ta2 ");
If (oTa2.selectionStart) {// non-IE browser
OTa2.selectionStart = I;
OTa2.selectionEnd = I;
} Else {// IE
Var range = oTa2.createTextRange ();
Range. move ("character", I );
Range. select ();
}
}
</Script>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.