2010-12-09 75 views
2

我有一个无序列表,其中包含1到3个列表项。无序列表(不幸)位于固定高度divoverflow: hidden之内。为集合中的每个元素设置CSS规则

<div id="container"> 
    <ul id="tweets"> 
    <li> 
     Lorem ipsum dolor sit amet, consectetur 
     adipiscing elit. Etiam est nisi, congue 
     id pulvinar eget. 
    </li> 
    <li> 
     Donec nisi dolor, molestie quis varius 
     a, dictum vel nunc. Morbi odio lorem, 
     viverra eu semper eu. 
    </li> 
    <li> 
     Mollis ac lorem. Aenean consequat 
     interdum mi, nec vestibulum metus mollis 
     non. Curabitur sed. 
    </li> 
    </ul> 
</div> 

如果有3个鸣叫,线高度必须不超过1em的完全配合在容器更。如果只有不到三条推文,线路高度可以达到1.5em以适应网站设计的其他部分。

我想要做一些jQuery魔术来动态更新行高。

var tweet_len = $("#tweets > li").size(); 
if (tweet_len == 0) { 
    // append a msg telling user there's no tweets 
    // (this message looks like a tweet and has line-height: 1.5em) 
} else if (tweet_len > 0 && tweet_len < 3) { 
    $("#tweets li").each(function(){ 
     $(this).css("line-height: 1.5em"); 
    }); 
} 

我试过使用上面的代码(第6-8行),但它不工作。 (我不认为我完全理解如何使用.each()。)

我应该在第6-8行上使用什么代码将行高更新为1.5em?

回答

1

你要通过2个PARAMS的CSS方法:

$(this).css("line-height", "1.5em"); 
+0

你是第一个几分之一秒的评论。恭喜! – Jazzerus 2010-12-09 23:06:17

2

所有其他答案当然有效,但请注意,你也可以简单地使用下面的代码来设置CSS,而无需手动迭代:

$("#tweets li").css("line-height", "1.5em"); 
+0

这就是我一开始想要做的,但我试图用一个参数而不是两个(没有意识到这是问题)。 – Jazzerus 2010-12-09 23:07:19

0

无需在JS做,你可以用CSS做什么(通过更有效率)

CSS :

#tweets {line-height: 1.5} 
#tweets.long-list {line-height: 1} 

请注意,行高被应用于UL(不是LIs),因为它是继承的。 确保删除任何明确设置LI上的行高的规则。如果你不能,你可能要针对李的上面:

#tweets li {line-height: 1.5} 
#tweets.long-list li {line-height: 1} 

现在,瘦JS部分:

var $tweets = $("#tweets"), // save for reuse 
    tweet_len = $tweets.children().size(); 


if (!tweet_len) { 
    // append a msg telling user there's no tweets 
} else if (tweet_len > 3) { 
    // only case where you actually need to change things 
    // we do that without traversing the dom and touching it only once 
    $tweets.addClass('long-list'); 
} 

,如果这是“活”的代码(例如,如果轮询的setInterval( )或住进去()或委托()回调)和行可以减少的数量,你必须明确地删除添加的类:

if (tweet_len > 3) { 
    $tweets.addClass('long-list'); 
} else { 
    $tweets.removeClass('long-list'); 
    if (!tweet_len) { 
     // append a msg telling user there's no tweets 
    } 
}