2011-08-01 55 views
3

我有一些問題,jQuery和我真的希望有人在那裏可以幫助孩子DIV如何改變HX標籤的動態大小!如果父div包含類X

我有以下HTML:

<div class="widgetContent"> 
     <div class="thumbNail"> </div> 
     <h4> 
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce feugiat mauris non 
      libero. 
     </h4> 
     <div class="clear"> 
     </div> 
     <span class="newsDate">10th March 2011</span> 
     <p class="widgetTexSummary"> 
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce feugiat ...</p> 
</div> 

<div class="widgetContent"> 
     <div class="widgetEventsDate"> 
      <span class="month">Mar</span> <span class="date">24</span></div> 
     <h4> 
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce feugiat mauris non 
      libero. 
     </h4> 
     <div class="clear"> 
     </div> 
     <span class="newsDate">10th March 2011</span> 
     <p class="widgetTexSummary"> 
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce feugiat ...</p> 
</div> 

及以下的jQuery:

if ($(".widgetContent:has(.thumbNail)")){ 
     $('h4').css('width', '100px'); 
    } 
    else{$('h4').css('width','195px');} 

的想法是,當我有類「縮略圖」一個孩子在插件的小部件中的H4將其大小動態變爲100px。在所有其他情況下,h4的大小不同。

任何人都可以幫助我嗎?

謝謝!

回答

2

首先,設置你的CSS默認寬度。

.widgetContent h4 { 
    width: 195px; 
} 

然後:

$('.widgetContent')  // all widgets 
    .has('.thumbNail')  // but only those with a thumbnail 
    .find('h4')    // find the <h4> children of those 
    .css('width', '100px'); // and set the style 
+0

+1簡潔,包羅萬象的解決方案 –

+0

對於像我這樣的新手來說,上面有很多道理!好的解決方案 – Vikita

+0

@Vikita現在用'.has()'改進而不是'.filter(':has(...)')' – Alnitak

1

你可以這樣做:

$(".widgetContent").each(function() { 
    if ($(this).find('.thumbNail').length) { 
     $(this).find('h4').css('width', '100px'); 
    } else { 
     $(this).find('h4').css('width', '195px'); 
    } 
}); 

小提琴這裏:http://jsfiddle.net/nicolapeluchetti/9jdnY/1/

+0

EFIDDLENOTFOUND – Alnitak

+0

現在的作品,它只是沒有將其保存在其他的時間:http://jsfiddle.net/nicolapeluchetti/9jdnY/1/ –

+0

謝謝,謝謝, 謝謝!!! – Vikita

1

如果我正確地讀你的問題,你可以這樣做......

$('.thumbNail + h4').css('fontSize','100px'); 

http://jsfiddle.net/jasongennaro/5Sf2B/

這基本上選擇旁邊的任何h4一個類.thumbNail的元素。

下面是一個更可讀的例子(在25像素):http://jsfiddle.net/jasongennaro/5Sf2B/1/

的「所有其它情況下」應處理在樣式表中。

不知道爲什麼你想要它那麼大,但是你去那裏;-)

編輯

我可能會錯誤地解釋了Q,雖然概念是相同的。如果你想改變h4,而不是font-sizewidth,則只是這樣做:

$('.thumbNail + h4').css('width','100px'); 

http://jsfiddle.net/jasongennaro/5Sf2B/2/

+0

嘗試使用'width'而不是'font-size'。 – Ben

+0

如果h4不是緊跟在縮略圖之後呢? – Alnitak

+0

@Ben做OP想要'寬度'?我以爲他想要'字體大小'。 ;-) –