2010-12-09 9 views
2

목록에 1 ~ 3 개의 목록이있는 정렬되지 않은 목록이 있습니다. 정렬되지 않은 목록은 고정 높이 div의 안쪽에 (불행하게도) overflow: 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 이하 여야합니다. 트윗이 3 개 미만인 경우 라인 높이는 사이트 디자인의 나머지 부분에 맞추기 위해 최대 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()를 사용하는 방법을 완전히 이해하지 못했다고 생각합니다.)

행 높이를 1.5em으로 업데이트하려면 6-8 행에 어떤 코드를 사용해야합니까?

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

답변

1

당신은 CSS의 방법이 PARAMS을 통과해야

css(propertyName, value)

그래서이 작동합니다

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

+0

처음으로 짧은 시간에 의견을 제시했습니다. 축하해! – Jazzerus

2

JQuery와 API에서 :

2

모든 다른 대답은 물론 유효합니다.

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

이것은 처음에 시도한 것이지만, 문제가 있다는 것을 깨닫지 않고 두 개의 매개 변수 대신 하나의 매개 변수를 사용하려고했습니다. – Jazzerus

0

당신이 (훨씬 더 효율적으로) CSS로 수행 할 수있는 JS에서 할 필요가 없습니다

CSS를 :하지만 당신은 단순히 수동으로 반복하지 않고 CSS를 설정하려면 다음 코드를 사용할 수 있습니다 :

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

줄 높이는 상속되므로 UL (LI가 아닌)에 적용됩니다. LI의 줄 높이를 명시 적으로 설정하는 규칙을 모두 삭제해야합니다. 당신은, 당신은 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을 가진 폴링 () 또는 live() 또는 delegate() 콜백 내부에서 행 수가 줄어들 수 있으므로 추가 된 클래스를 명시 적으로 제거해야합니다.

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 
    } 
} 
관련 문제