javascript jQuery 检查是否设置了 .css 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18413684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery check if .css property was set
提问by TatiOverflow
My code looks like this
我的代码看起来像这样
if($(element).css("background-color") == null){
$(element).css("background-color", "white");
}
I want to make sure that if the color wasn't set in the style.css
file, I add it. But that code is not working. It's always returning rgba(0,0,0,0)
. The browser I am working with is Chrome.
我想确保如果style.css
文件中没有设置颜色,我会添加它。但该代码不起作用。它总是回来rgba(0,0,0,0)
。我正在使用的浏览器是 Chrome。
Is there another way to check if the color wasn't set?
是否有另一种方法来检查颜色是否未设置?
回答by vol7ron
CSS:
CSS:
.background-set { background-color: white; }
jQuery:
jQuery:
var $el = $(element);
if( !$el.hasClass('background-set') ){
$el.addClass('background-set');
}
Though I'm not sure why you'd need to check. You can just add it without the condition.
虽然我不确定你为什么需要检查。您可以在没有条件的情况下添加它。
Alternatively:
或者:
if ( $el.prop('style').backgroundColor == '' ) {
...
}
or
或者
if ( $el.get(0).style.backgroundColor == '' ) {
...
}
回答by Limescale
The method suggested by elclanrs is the most elegant way of handling this and should be the preferred method. However, for the sake of sating curiosity, you could achieve the same result using a jQuery Attribute Contains Selector.
elclanrs 建议的方法是最优雅的处理方法,应该是首选方法。但是,为了满足好奇心,您可以使用jQuery Attribute Contains Selector实现相同的结果。
$("div[style*='background-color']").text("I have a background color!");