Js obtains the relative/absolute position of an element on the page.

Source: Internet
Author: User

In js, the algorithm for retrieving the position of an element on the page is very simple, as long as it is the position of the element on the page = the position of the element relative to the browser window + the value of the browser scroll bar, the absolute location is almost the same. I will introduce it to you as an example below.

We can first use the getBoundingClientRect () method to obtain the position of an element relative to the browser window {This method returns an Object, that is, an Object, which has four attributes: top, left, right, bottom}

Then, calculate the value of the browser scroll bar and add the two values to get the position of the element on the page!

If we want to obtain the Coordinate Position of element obj in the upper left corner of the page, the calculation formula is as follows:

The Code is as follows: Copy code

// Chromeunable to identify document.doc umentElement compatible with document. body
Var stopdeskdocument.doc umentElement. scrollTop = 0? Document. body. scrollTop: document.doc umentElement. scrollTop;
Var sLeft = document.doc umentElement. scrollLeft = 0? Document. body. scrollLeft: document.doc umentElement. scrollLeft;

The Left value of this obj element on the page = obj. getBoundingClientRect (). left + sLeft

The Top value of this obj element on the page = obj. getBoundingClientRect (). top + sTop
 

Note: The getBoundingClientRect () method is only supported by ie. FF3.0 + and Opera9.5 + support this method now. It can be said that the efficiency of obtaining the page element location can be greatly improved!

So how can we get the absolute location?

The Code is as follows: Copy code

Function findPosX (obj ){
Var curleft = 0;

If (obj. offsetParent) {// returns the parent element. Most of them indicate that offsetParent returns the body.
While (obj. offsetParent) {// traverses all parent class Elements
Curleft + = obj. offsetLeft; // left margin of the current element
Obj = obj. offsetParent;
}
} Else if (obj. x) curleft + = obj. x;
Return curleft;
}


I usually use the offsetLeft and offsetTop methods of the accumulate element offsetParent until the top layer of the DOM. In actual work, some problems occur, that is, when the element has a border, problems may occur, and the calculated position is not very accurate. especially in IE and other browsers.

The following is an example.

The Code is as follows: Copy code
Function getElementPos (elementId)
{
Var ua = navigator. userAgent. toLowerCase ();
Var isOpera = (ua. indexOf ('Opera ')! =-1 );
Var isIE = (ua. indexOf ('msie ')! =-1 &&! IsOpera); // not opera spoof
Var el = document. getElementById (elementId );

If (el. parentNode = null | el. style. display = 'None ')
{
Return false;
}


Var parent = null;
Var pos = [];
Var box;

If (el. getBoundingClientRect) // IE
{
Box = el. getBoundingClientRect ();
Var scrollTop = Math.max(document.doc umentElement. scrollTop, document. body. scrollTop );
Var scrollLeft = Math.max(document.doc umentElement. scrollLeft, document. body. scrollLeft );
Return {x: box. left + scrollLeft, y: box. top + scrollTop };
}
Else if (document. getBoxObjectFor) // gecko
{
Box = document. getBoxObjectFor (el );
Var borderLeft = (el. style. borderLeftWidth )? ParseInt (el. style. borderLeftWidth): 0;
Var borderTop = (el. style. borderTopWidth )? ParseInt (el. style. borderTopWidth): 0;
Pos = [box. x-borderLeft, box. y-borderTop];
}
Else // safari & opera
{
Pos = [el. offsetLeft, el. offsetTop];
Parent = el. offsetParent;

If (parent! = El)
{
While (parent)
{
Pos [0] + = parent. offsetLeft;
Pos [1] + = parent. offsetTop;
Parent = parent. offsetParent;
}
}

If (ua. indexOf ('Opera ')! =-1 | (ua. indexOf ('safari ')! =-1 & el. style. position = 'absolute '))
{
Pos [0]-= document. body. offsetLeft;
Pos [1]-= document. body. offsetTop;
}
}

If (el. parentNode)
{
Parent = el. parentNode;
}
Else
{
Parent = null;
}

While (parent & parent. tagName! = 'Body' & parent. tagName! = 'Html ')
{// Account for any scrolled ancestors
Pos [0]-= parent. scrollLeft;
Pos [1]-= parent. scrollTop;

If (parent. parentNode)
{
Parent = parent. parentNode;
}
Else
{
Parent = null;
}
}

Return {x: pos [0], y: pos [1]};
}

Call method:

The Code is as follows: Copy code
Var pos = getElementPos (ElementId );

Pos. y // identify the distance from the top

Pos. x // distance to the left

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.