【jQuery】親要素からの距離を求める

親要素のTOPから子要素の距離をもとめる。 .height() .offset() .scrollTop() .position()

by tea4two

HTML

<p id="obst">80px obstrucles<br />obstrucles</p>
<div id="parent">
  <div id="pos1">Has a position of 0px from top of containing parent el.</div>
  <div id="pos2">Has a position of 40px from top of containing parent el.</div>
</div>

CSS

#obst { height: 80px; background: #fc0e0e;}
#parent {background: #ccc; }
#pos1 {background: #ecc; height: 180px;}
#pos2 {background: #00f; height: 40px; }

JavaScript

var pHeight = $('#parent').height();
var dist = $('#pos2').offset().top;
var pDist = $('#parent').offset().top;

var cDist = dist - pDist;
alert(pDist);
alert(dist);
alert(cDist);