问题描述
我正在尝试编写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,如何仅设置此元素的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!