如何使用jQuery检查css值?

zec*_*ude 13 css jquery

用户点击表格行后,我希望它检查表格行的背景颜色是否为白色,如果是,则将颜色更改为浅蓝色.

我使用的代码不起作用.这里是:

$("#tracker_table tr#master").click(function(){
  if($(this).css("background-color") == "#FFFFFF") { 
    $(this).css("background-color", "#C2DAEF");
  }
});
Run Code Online (Sandbox Code Playgroud)

我认为我的if语句有问题.如何使用jQuery检查css值?

Alc*_*nja 22

看起来它在表单中返回rgb(x, y, z),因此您的代码应该是:

$("#tracker_table tr#master").click(function(){
  if($(this).css("background-color") == "rgb(255, 255, 255)") { 
    $(this).css("background-color", "#C2DAEF");
  }
});
Run Code Online (Sandbox Code Playgroud)

编辑:话虽如此,我建议你使用类而不是直接检查/设置css属性.像这样的东西:

$("#tracker_table tr#master").click(function(){
  if(!$(this).hasClass("selected")) { 
    $(this).addClass("selected");
  }
});
Run Code Online (Sandbox Code Playgroud)

CSS:

tr { background-color: #FFFFFF; }
tr.selected { background-color: #C2DAEF; }
Run Code Online (Sandbox Code Playgroud)