2012-04-18 62 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);