2010-12-09 69 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 
    } 
}