2012-04-18 64 views
0

我想檢查圖像的高度(頁面上有多個這樣的元素)。如果高度大於66px,我想應用等於其高度一半的負頂邊距。jQuery:根據if語句添加css

以下代碼不會執行任何操作。我的if語句有什麼問題?

if($('.topstories a.image img').height() > 66){ 
    var margintop = -0.5 * ($(this).height() - 66); 
    $(this).css('margin-top', 'margintop'); 
} 

回答

2

我不知道你的函數的其餘部分,但你要經過的每個圖像,你需要使用一個循環或每個()。喜歡的東西:

$('.topstories a.image img').each(function(){ 
    if($(this).height() > 66)){ 
     var margintop = 0.5 * ($(this).height()); 
     $(this).css('margin-top', '-' + margintop); 
    } 
}); 

我想,你在數學運算符的66減法也導致一個問題 - 如果圖像高度爲67,和你減去66,你會得到1.1 * 0.5排序等於0,所以你不會看到效果。

+0

謝謝 - 每個()都是我所缺少的。 – 2012-04-19 23:42:59

4

您已將值放到引號中,因此將其視爲字符串文本(在本例中爲無效值)。嘗試:

$(this).css('margin-top', margintop); 
+0

謝謝,但style屬性仍然是空的... – 2012-04-18 12:16:02

+0

您確定您將樣式應用於正確的元素嗎?在這種情況下,這是什麼?你有沒有嘗試指定選擇器來代替這個?像$(「#idOfImage」).css('margin-top',margintop); – mattytommo 2012-04-18 12:21:56

1

更換

$(this).css('margin-top', 'margintop'); 

$(this).css('margin-top', margintop);