0

我有一系列文章,每页重复 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})

});
4

1 回答 1

0

假设您的问题总是在<h2>您的第一个元素之前只有一个元素<p>,您可以使用元素的高度(outerHeight<h2>而不是计算偏移量作为快捷方式:

$(".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()
    );
});
于 2013-02-15T18:53:09.453 回答