Jquery gets an example of the distance between the div distance window and the parent dv

  • 2020-03-26 21:21:13
  • OfStack

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

(1) introduce jquery. Offset (). Top/left
CSS:

 
*{ 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:
 
<body> 
<div class="a"> a<div> 
<div class="parentBox"> 
<div class="innerBox">innerBox</div> 
</div> 
</body> 

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

Here 280px= a.height/200px + parentbox.padding -top/30px + parentbox.margin-top /40px + innerbox.margin-top /10px;
// if parentBox sets position: relative; InnerBox sets position: absolute; And the innerBox sets 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 referenced by the inner border of the upper-left corner of the parent div.
// if the innerBox has a border then 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 div must be absolutely positioned
CSS:
 
*{ 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:
The same code at the page code block index 1
Js:
The same code at the page code block index 2


Related articles: