Home  >  Article  >  Web Front-end  >  javascript accurately obtains the position of page elements_javascript skills

javascript accurately obtains the position of page elements_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:37:17925browse
Copy code The code is as follows:

//Get the x coordinate of the element
function pageX(elem) {
return elem.offsetParent?(elem.offsetLeft pageX(elem.offsetParent)):elem.offsetLeft;
}
//Get the y coordinate of the element
function pageY(elem) {
return elem.offsetParent?(elem.offsetTop pageY(elem.offsetParent)):elem.offsetTop;
}

It seems that this great master was in a hurry when publishing this book, and there were many mistakes. In the end, the master also discovered that there was a problem with these two functions and did not apply them to JQuery. Since it is calculated in an accumulative way, as long as there is a problem with one element, it may be increased layer by layer, so I abandon this method when accurately obtaining the style attributes. The main miscalculations refer to the master’s conclusion:
Handling table border offsets.
Fixed elements positioned.
Scroll offsets within another element.
Borders of overflowed parent elements.
Miscalculation of absolutely positioned elements.
javascript accurately obtains the position of page elements_javascript skills

With all new browsers supporting IE’s getBoundingClientRect method, we can use a simpler, faster and safer method to locate page elements. getBoundingClientRect returns a set, which are the coordinates of the four corners of the element in the browser's visual area.

However, it has a strange problem in the standard mode of IE. The html element has a border, the default is 2px, and cannot be modified; the quirks mode does not have it. For details, see http://msdn.microsoft.com/en-us/library/ms536433(VS.85).aspx

This method retrieves an object that exposes the left, top, right, and bottom coordinates of the union of rectangles relative to the client's upper-left corner. In Microsoft Internet Explorer 5, the window's upper-left is at 2,2 (pixels) with respect to the true client.

Let’s do some tests (please do it in IE6 and IE8 respectively):

1. Standard mode, no html border reset


Statement:
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