2013-02-15 136 views
0

我有一系列在每个页面上重复10次的文章。该结构是像这样:使用jQuery查找一个元素相对于另一个元素的距离

<article class="postWrap"> 
    <h2>Title</h2> 
    <p>Here is text</p> 
</article> 

我需要找到距离p标签是对文章的顶部。因此,根据标题的长度,p标签距文章顶部的距离可能会有所不同。最好的方法很可能是使用offset(),但我无法正常工作。

感谢

UPDATE:

这里是工作的代码我写的,但我想有是绕了一个更好的办法:从你的问题假设

$(".postWrap").each(function(){ 
     var postWrap = $(this).offset().top; 
     var firstP = $(this).find("p:first-of-type").offset().top; 
     var diff = firstP - postWrap; 
     var meta = $(this).find(".meta").css({'marginTop' : diff}) 

}); 

回答

0

有始终正好是您的第一个<p>之前的一个<h2>元素,您可以使用<h2>元素的高度(outerHeight)代替计算偏移量作为快捷键:

$(".postWrap").each(function(){ 
    var diff = $(this).find('h2:first').outerHeight(); 
    var meta = $(this).find(".meta").css('margin-top', diff); 
}); 

从你的榜样,我没有得到什么.meta是的,但你可以试试,并告诉我,如果它按预期工作。如果情况更好,你也可以使用innerHeight

编辑:或作为 “一个班轮” 不声明变量:

$(".postWrap").each(function(){ 
    $(this).find(".meta").css(
     'margin-top', 
     $(this).find('h2:first').outerHeight() 
    ); 
}); 
相关问题