简体   繁体   English

jQuery检查元素是否具有特定的样式属性(显示)

[英]jQuery check if element has a specific style property (display)

I need to have a if/else statement inside a function. 我需要在函数内部有一个if / else语句。 How do you check if an element (eg #cadrage) has a display style property? 如何检查元素(例如#cadrage)是否具有显示样式属性? This is what I have found around the net and yet, it is not working.. 这是我在网上发现的,然而,它不起作用..

if( $('#cadrage').attr('style').display == 'block' ) {
      // do something
} else {
      // do something
}

The jQuery .css() function seems to be what you want. jQuery .css()函数似乎就是你想要的。

if( $('#cadrage').css('display') == 'block' ) {
   console.log('It equal block');
} else {
   console.log('It did not equal block');
}

http://jsfiddle.net/SamMonk/FtP6W/ http://jsfiddle.net/SamMonk/FtP6W/

Your code doesn't work because style property only contains inline styles, not those coming from a stylesheet. 您的代码不起作用,因为style属性仅包含内联样式,而不包含来自样式表的样式。

To get the computed style, you can use css method: 要获取计算样式,可以使用css方法:

$('#cadrage').css('display') == 'block'

Not exactly what you ask for, but perhaps what you are looking for... 不完全是你要求的,但也许你正在寻找...

You can use the :visible pseudo selector to check if the element is visible: 您可以使用:visible伪选择器来检查元素是否可见:

if( $('#cadrage').is(':visible')) {
      // do something
} else {
      // do something
}

Note that this doesn't actually check the display style, but rather if the element has a size so that it could be seen in the page. 请注意,这实际上并不检查display样式,而是元素的大小是否可以在页面中看到。

Try this: 尝试这个:

if( $('#cadrage').css('display')== 'block' ) {
      // do something
} else {
      // do something
}

You can get your element display property with the following code snippet 您可以使用以下代码段获取元素显示属性

$('#cadrage').css('display');

Note that the css method can return any css property of your element so it is very handy. 请注意, css方法可以返回元素的任何css属性,因此非常方便。 Therefore your statement code will be: 因此,您的语句代码将是:

if( $('#cadrage').css('display').display == 'block' ) {
      // do something
} else {
      // do something
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM