我有一系列的文章,每页重复10次。结构是这样的:
<article class="postWrap">
<h2>Title</h2>
<p>Here is text</p>
</article>我需要找出p标记到文章顶部的距离。因此,根据标题的长度,p标签到文章顶部的距离可能会有所不同。最好的方法很可能是使用offset(),但是我很难让它正常工作。
谢谢
更新:
以下是我写的工作代码,但我想还有更好的方法:
$(".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})
});发布于 2013-02-16 02:53:09
根据您的问题,假设在第一个<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,如果它更适合的话。
EDIT:或作为不声明变量的“一行程序”:
$(".postWrap").each(function(){
$(this).find(".meta").css(
'margin-top',
$(this).find('h2:first').outerHeight()
);
});https://stackoverflow.com/questions/14900741
复制相似问题