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

Example of jquery getting the distance between a div and the window and the parent dv_jquery

WBOY
Release: 2016-05-16 17:20:36
Original
1305 people have browsed it

In jquery, jquery.offset().top/left is used to get the distance of the div from the window, and jquery.position().top/left is used to get the distance from the parent div (it must be an absolutely positioned div).

(1) First introduce jquery.offset().top / left
css:

Copy code The code is as follows:

*{ margin: 0px; padding: 0px; }
div{ margin: 0px auto; }
.a{ width: 960px; height: 200px; }
.parentBox{ padding: 30px; margin-top: 40px; width: 960px; height: 300px; }
.innerBox{ padding: 20px; margin-top: 10px; width: 400px; height: 100px; }

html:
Copy code The code is as follows:

< ;body>
a


innerBox



js:
Copy code The code is as follows:

$(function(){
var_offsetTop = $(".innerBox").offset().top; //280px
})

280px here= a.height/200px parentBox.padding-top/30px parentBox.margin-top/40px innerBox.margin-top/10px;
//If the parentBox here sets position : relative; innerBox sets position: absolute; and innerBox sets top: 40px;
//At this time, the value of _offsetTop is 290px = a.height/200px parentBox.margin-top/40px innerBox.margin-top/10px ineBox.top/40px;
//Because the absolute definition is based on the inner border of the upper left corner of the parent div as the reference coordinate.
//If the innerBox sets a border, add the border value

(2) jqury.position().top /left is used to get the distance between the child div and the parent div, and the child The div must be absolutely positioned
css:
Copy code The code is as follows:

*{ margin: 0px; padding: 0px; }
div{ margin: 0px auto; }
.a{ width: 960px; height: 200px; }
.parentBox{ padding: 30px; margin-top: 40px ; width: 960px; height: 300px; position: relative; }
.innerBox{ padding: 20px; margin-top: 10px; width: 400px; height: 100px; position: absolute; }

html:
Copy code The code is as follows:


< ;div class="a"> a


innerBox



$(function(){
var_offsetTop = $(".innerBox").offset().top; //280px
})
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