JavaScript to get the pixel position of the text box cursor

Source: Internet
Author: User

This article mainly obtains the pixel positions of the textarea and input cursor, that is, the offsetLeft and offsetTop of the cursor. The following results can be achieved:

First of all, the code found on the internet is how to get the input cursor position. The following code shows how to get the character position of the cursor, for example, for the string "He | llo World !" The returned cursor is the number of characters 2 before the cursor, not the pixel position of the cursor on the page. Of course, this code can assist in obtaining the pixel position of the cursor.

// Obtain the cursor position in the text box
Function _ getFocus (elem ){
Var index = 0;
If (document. selection) {// IE Support
Elem. focus ();
Var Sel = document. selection. createRange ();
If (elem. nodeName = 'textarea ') {// TEXTAREA
Var Sel2 = Sel. duplicate ();
Sel2.moveToElementText (elem );
Var index =-1;
While (Sel2.inRange (Sel )){
Sel2.moveStart ('character ');
Index ++;
};
}
Else if (elem. nodeName = 'input') {// INPUT
Sel. moveStart ('character ',-elem. value. length );
Index = Sel. text. length;
}
}
Else if (elem. selectionStart | elem. selectionStart = '0') {// Firefox support
Index = elem. selectionStart;
}
Return (index );
}
For ie browsers, the following code 1 is more convenient.
// Code 1
If (document. selection ){
Elem. focus ();
Var Sel = document. selection. createRange ();
Return {
Left: Sel. boundingLeft,
Top: Sel. boundingTop,
Bottom: Sel. boundingTop + Sel. boundingHeight
};
}

Firefox and other browsers are simulated, as shown in. First, copy the style of the input area to a div layer (clone layer), then add the characters before the cursor to the text child layer in the clone layer, and add the focus layer after the text child layer, the focus layer contains the character "|" to simulate the cursor, and obtains the pixel Coordinate Position of the text cursor by obtaining the offset of the focus layer.

The specific implementation code is as follows:

Var kingwolfofsky = {
/**
* Obtain the coordinates of the input cursor on the page
* @ Param {HTMLElement} element of the input box
* @ Return {Object} returns left and top, bottom
*/
GetInputPositon: function (elem ){
If (document. selection) {// IE Support
Elem. focus ();
Var Sel = document. selection. createRange ();
Return {
Left: Sel. boundingLeft,
Top: Sel. boundingTop,
Bottom: Sel. boundingTop + Sel. boundingHeight
};
} Else {
Var that = this;
Var cloneDiv = '{$ clone_div}', cloneLeft = '{$ cloneLeft}', cloneFocus = '{$ cloneFocus}', cloneRight = '{$ cloneRight }';
Var none = '<font style = "white-space: pre-wrap;"> </font> ';
Var div = elem [cloneDiv] | document. createElement ('div '), focus = elem [cloneFocus] | document. createElement ('font ');
Var text = elem [cloneLeft] | document. createElement ('font ');
Var offset = that. _ offset (elem), index = this. _ getFocus (elem), focusOffset = {left: 0, top: 0 };

If (! Elem [cloneDiv]) {
Elem [cloneDiv] = div, elem [cloneFocus] = focus;
Elem [cloneLeft] = text;
Div. appendChild (text );
Div. appendChild (focus );
Document. body. appendChild (div );
Focus. innerHTML = '| ';
Focus.style.css Text = 'display: inline-block; width: 0px; overflow: hidden; z-index:-100; word-wrap: break-word; word-break: break-all ;';
Div. className = this. _ cloneStyle (elem );
Div.style.css Text = 'visibility: hidden; display: inline-block; position: absolute; z-index:-100; word-wrap: break-word; word-break: break-all; overflow: hidden ;';
};
Div. style. left = this. _ offset (elem). left + "px ";
Div. style. top = this. _ offset (elem). top + "px ";
Var strTmp = elem. value. substring (0, index ). replace (/</g, '<'). replace (/>/g, '> '). replace (/\ n/g, '<br/> '). replace (/\ s/g, none );
Text. innerHTML = strTmp;

Focus. style. display = 'inline-Block ';
Try {focusOffset = this. _ offset (focus);} catch (e ){};
Focus. style. display = 'none ';
Return {
Left: focusOffset. left,
Top: focusOffset. top,
Bottom: focusOffset. bottom
};
}
},

// Clone element style and return class
_ CloneStyle: function (elem, cache ){
If (! Cache & elem ['$ {cloneName}']) return elem ['$ {cloneName}'];
Var className, name, rstyle =/^ (number | string) $ /;
Var rname =/^ (content | outline | outlineWidth) $ // Opera: content; IE8: outline & outlineWidth
Var cssText = [], sStyle = elem. style;

For (name in sStyle ){
If (! Rname. test (name )){
Val = this. _ getStyle (elem, name );
If (val! = ''& Rstyle. test (typeof val) {// Firefox 4
Name = name. replace (/([A-Z])/g, "-$1"). toLowerCase ();
CssText. push (name );
CssText. push (':');
CssText. push (val );
CssText. push (';');
};
};
};
CssText = cssText. join ('');
Elem ['$ {cloneName}'] = className = 'clone '+ (new Date). getTime ();
This. _ addHeadStyle ('.' + className + '{' + cssText + '}');
Return className;
},

// Insert a style to the page header
_ AddHeadStyle: function (content ){
Var style = this. _ style [document];
If (! Style ){
Style = this. _ style [document] = document. createElement ('style ');
Document. getElementsByTagName ('head') [0]. appendChild (style );
};
Style. styleSheet & (style.styleSheet.css Text + = content) | style. appendChild (document. createTextNode (content ));
},
_ Style :{},

// Obtain the final Style
_ GetStyle: 'getcomputedstyle' in window? Function (elem, name ){
Return getComputedStyle (elem, null) [name];
}: Function (elem, name ){
Return elem. currentStyle [name];
},

// Obtain the cursor position in the text box
_ GetFocus: function (elem ){
Var index = 0;
If (document. selection) {// IE Support
Elem. focus ();
Var Sel = document. selection. createRange ();
If (elem. nodeName = 'textarea ') {// TEXTAREA
Var Sel2 = Sel. duplicate ();
Sel2.moveToElementText (elem );
Var index =-1;
While (Sel2.inRange (Sel )){
Sel2.moveStart ('character ');
Index ++;
};
}
Else if (elem. nodeName = 'input') {// INPUT
Sel. moveStart ('character ',-elem. value. length );
Index = Sel. text. length;
}
}
Else if (elem. selectionStart | elem. selectionStart = '0') {// Firefox support
Index = elem. selectionStart;
}
Return (index );
},

// Obtain the position of the element on the page
_ Offset: function (elem ){
Var box = elem. getBoundingClientRect (), doc = elem. ownerDocument, body = doc. body, docElem = doc.doc umentElement;
Var clientTop = docElem. clientTop | body. clientTop | 0, clientLeft = docElem. clientLeft | body. clientLeft | 0;
Var top = box. top + (self. pageYOffset | docElem. scrollTop)-clientTop, left = box. left + (self. pageXOffset | docElem. scrollLeft)-clientLeft;
Return {
Left: left,
Top: top,
Right: left + box. width,
Bottom: top + box. height
};
}
};

Function getPosition (ctrl ){
Var p = kingwolfofsky. getInputPositon (ctrl );
Document. getElementById ('show'). style. left = p. left + "px ";
Document. getElementById ('show'). style. top = p. bottom + "px ";
}

The test page is as follows:

<! DOCTYPE html> 

Tip: the code can be modified before running!

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.