如果条件为true或false,如何仅设置此元素的样式?

时间:2014-04-04 13:47:39

标签: javascript jquery

我正在尝试编写jQuery,它将循环遍历每个具有类名.content_txt的div,并检查其高度是否超过60px。如果为true,则将该元素设置为height:auto;如果为false,则将此元素高度设置为60px

问题是页面上有更多的div。如何根据条件仅设置特定div的样式?

是否可以使用jQuery向此元素属性样式添加规则而无需重写现有规则?例如,在我的HTML文档中有这个元素的结构:

<div class='content_txt' style="background-color:f00;">..content</div>

保持背景颜色并添加height参数。

我的jQuery:

$('.content_txt').each(function(){
     if($(this).height > 60){
       $(this).css('height','auto');
     }else{
       $(this).css('height','60px');        
     }
});

3 个答案:

答案 0 :(得分:2)

jquery的高度是函数而不是属性。所以使用.height()

 if($(this).height() > 60){
    //rest code
 }

答案 1 :(得分:1)

$('.content_txt').each(function(){
     if($(this).height() > 60){
       $(this).css('height','auto');
     }else{
       $(this).css('height','60px');        
     }
});

height()

答案 2 :(得分:0)

height是一个函数而不是属性。

所以,你必须做if($(this).height() > 60){}

相关问题