如何使用 jQuery 检查 css 值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2941213/
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
How do I check for a css value using jQuery?
提问by zeckdude
After the user clicks on a table row, I want it to check if the table row's background-color is white, and if so, it will change the color to light blue.
用户单击表格行后,我希望它检查表格行的背景颜色是否为白色,如果是,则将颜色更改为浅蓝色。
The code I am using is not working. Here it is:
我正在使用的代码不起作用。这里是:
$("#tracker_table tr#master").click(function(){
if($(this).css("background-color") == "#FFFFFF") {
$(this).css("background-color", "#C2DAEF");
}
});
I think there is something wrong with my if statement. How do I check for a css value using jQuery?
我认为我的 if 语句有问题。如何使用 jQuery 检查 css 值?
回答by Alconja
Looks like it gets returned in the form rgb(x, y, z)
, so your code should be:
看起来它以 form 返回rgb(x, y, z)
,所以你的代码应该是:
$("#tracker_table tr#master").click(function(){
if($(this).css("background-color") == "rgb(255, 255, 255)") {
$(this).css("background-color", "#C2DAEF");
}
});
Edit: That being said, I'd suggest you use classes instead of inspecting/setting css properties directly. Something like this:
编辑:话虽如此,我建议您使用类而不是直接检查/设置 css 属性。像这样的东西:
$("#tracker_table tr#master").click(function(){
if(!$(this).hasClass("selected")) {
$(this).addClass("selected");
}
});
Css:
css:
tr { background-color: #FFFFFF; }
tr.selected { background-color: #C2DAEF; }
回答by Ken Redler
While this may work, in effect you are storing information in the form of colors, and then retrieving and comparing this information later. Alconja suggests an approach that will work, but ultimately you may be better off working with classes, whose names can be defined by you to carry appropriate meaning. It's much friendlier and less brittle to have something like this:
虽然这可能有效,但实际上您是以颜色的形式存储信息,然后稍后检索和比较这些信息。Alconja 提出了一种可行的方法,但最终您最好使用类,类的名称可以由您定义以具有适当的含义。拥有这样的东西要友好得多,也不那么脆弱:
$('#tracker_table tr#master').click( function(){
if ( $(this).hasClass('something') ) {
$(this).removeClass('something').addClass('something_else');
}
})
回答by Touseef Murtaza
if you are using native javascript, you can try
如果您使用的是本机 javascript,则可以尝试
document.getElementById("#SELECTOR").style.("STYLE_PROPERTY") == VALUE;
or
或者
If you are using jQuery you can try something like
如果您使用的是 jQuery,您可以尝试类似
$("#SELECTOR").css("STYLE_PROPERTY") == VALUE_TO_MATCH