Home > Web Front-end > JS Tutorial > body text

js gets the absolute position of an element in the browser_javascript skills

WBOY
Release: 2016-05-16 18:22:28
Original
1380 people have browsed it

JavaScript provides attributes for obtaining the position of HTML elements:

HTMLElement.offsetLeft
HTMLElement.offsetHeight
However, it should be noted that the values ​​stored in these two attributes are not the relative values ​​of the element to the entire browser. The absolute position of the canvas, but the relative position relative to the position of its parent element, that is to say, these two values ​​​​are calculated based on the upper left corner of the parent element being the (0,0) point. So how to get the absolute position of an HTML element? You can use the following function:

Copy code The code is as follows:

//Get the vertical coordinate of the element
function getTop(e){
var offset=e.offsetTop;
if(e.offsetParent!=null) offset =getTop(e .offsetParent);
return offset;
}
//Get the abscissa coordinate of the element
function getLeft(e){
var offset=e.offsetLeft;
if(e. offsetParent!=null) offset =getLeft(e.offsetParent);
return offset;
}

The principle is to use the HTMLElement.offsetParent attribute, if the parent element of the current element is not empty (null), then add the current offsetTop to the original offsetTop, then continue to obtain the offsetTop of the parent element's parent element, then add it, and finally recurse the ordinate of the element relative to the entire browser canvas. The same goes for the abscissa.
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template