如果条件为true或false,如何仅设置此元素的样式? [英] How to style only this element if condition is true or false?

查看:86
本文介绍了如果条件为true或false,如何仅设置此元素的样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write jQuery that will loop over every div with the class name .content_txt and check its height is over 60px. If true, then set that element to height:auto; if false then set this element height to 60px.

问题是页面上具有该类的div较多.如何根据条件仅设置特定div的样式?

The problem is that there are more divs with that class on page. How do I style only the specific div based on the condition?

是否可以在不重写现有规则的情况下使用jQuery向该元素属性样式添加规则?例如,在我的HTML文档中,该元素的结构如下:

Is it possible to add a rule to this element attribute style with jQuery without rewriting existing rules? For example, in my HTML document there is this structure of this element:

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

保留background-color并添加height和参数.

keep background-color and add height with parameter.

我的jQuery:

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

推荐答案

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

height of jquery is function and not property. so use .height():

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

这篇关于如果条件为true或false,如何仅设置此元素的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆