Jquery in jquery. offset (). top/left is used to obtain the distance between the div and the window. jquery. position (). top/left is used to obtain the distance from the parent div (it must be an absolutely positioned div ).
(1) first introduce jquery. offset (). top/left
Css:
Copy codeThe 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 codeThe Code is as follows:
<Body>
<Div class = "a"> a <div>
<Div class = "parentBox">
<Div class = "innerBox"> innerBox </div>
</Div>
</Body>
Js:
Copy codeThe Code is as follows:
$ (Function (){
Var_offsetTop = $ (". innerBox"). offset (). top; // 280px
})
280px = a. height/200px + parentBox. padding-top/30px + parentBox. margin-top/40px + innerBox. margin-top/10px;
// If position: relative; innerBox is set to position: absolute in parentBox, and innerBox is set to top: 40px;
// 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 in the upper left corner of the parent div as the reference coordinate.
// Add the border value if the innerBox has a border.
(2) jqury. position (). top/left is used to obtain the distance between the sub-div and the parent div, and the sub-div must be absolutely located.
Css:
Copy codeThe 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 codeThe Code is as follows:
<Body>
<Div class = "a"> a <div>
<Div class = "parentBox">
<Div class = "innerBox"> innerBox </div>
</Div>
</Body>
Js:
Copy codeThe Code is as follows:
$ (Function (){
Var_offsetTop = $ (". innerBox"). offset (). top; // 280px
})