JavaScript gets the cursor position and sets the cursor position

Source: Internet
Author: User

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.



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.