jQuery获得前3个li标签的高度

时间:2011-05-26 12:48:03

标签: javascript jquery jcarousel

我正在填写一个包含动态内容的无序列表,列表高度将填充内容,是否有人知道如何在无序列表中获得前3个li标签的高度?

产生的动态内容可能如下所示,所以我只想计算前3个li标签的高度。

<ul>
<li>23 Feb 2011<br />Synergy Launch new website...<br />Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc gravida lacus a ligula dictum dignissim....</li>
<li>23 Feb 2011<br />Expat children "receive improv...<br />Expat children enjoy a better standard of education whilst living abroad compared to their home country according to the HSBC Offshore Offspring Report,...</li>
<li>25 Feb 2011<br />London Market favours Landlord...<br />The lettings market has swung dramatically in favour of landlords as an average six applicants chase every available property in London. This is a dramatic rise...</li>
<li>23 Feb 2011<br />Synergy Launch new website...<br />Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc gravida lacus a ligula dictum dignissim....</li>
</ul>

感谢您的帮助 学家

4 个答案:

答案 0 :(得分:20)

这为您提供了所有高度......但您可以轻松地将所需的代码放在函数中,以便在每个列表项上执行某些操作。

var sum = 0;

$('li:lt(3)').each(function() {
   sum += $(this).height();
});

http://jsfiddle.net/rnpAE/1/

编辑:$('li').nextUntil(':eq(2)')缩短为$('li:lt(3)')

答案 1 :(得分:4)

如果您想单独计算它们,请使用eq选择器

http://api.jquery.com/eq-selector/

var liHeight = $('li:eq(0)').outerHeight(); // Obtains height of first li

答案 2 :(得分:1)

首先我将var设置为减1项...

var liTotalHeight = -24;

然后,对于每个项目,我添加li的高度..

liTotalHeight = liTotalHeight + $(this).outerHeight();

然后我设置ul的scrollTop ...

$(this).parent().scrollTop(liTotalHeight);

有点hacky,但最适合我

答案 3 :(得分:0)

$('li').height(); // First
$('li').next().height(); // Second
$('li').next().next().height(); // Third

如果要包含填充/边距,请使用outerHeight