问题
I'm trying to change the background of an element on click based on the current color.
Here's the relevant html:
<div id="rect" style="height: 100px; width:300px; background: red">
</div>
and my jquery attempt:
$("#rect").click(function() {
if ($(this).css('background') == 'red') {
$(this).css('background','blue');}
else {$(this).css('background','yellow');}
});
I'm always getting a yellow box; the 'true' condition never fires.
What am I doing wrong?
回答1:
UPDATE
I found one exception, as expected, in IE. To account for IE exception, simply use jQuery's .browser Method. I've added this to below example code.
Try:
$("#rect").click(function() {
var red = $.browser.msie ? "red" : "rgb(255, 0, 0)";
if ($(this).css('background-color') == red) {
$(this).css('background','blue');}
else {$(this).css('background','yellow');}
});
As I explained in my comments, jQuery breaks down each part of CSS property "background", thus you need to call the exact Property you want, in this case background-color
. Also, jQuery returns color values as RGB style, thus red would be rgb(255, 0, 0)
. Now this doesn't stop .css("background"
from being useful to SET background, just remember, just like css, background will override all other background-direct properties.
Apparently someone made a jsFiddle example for me. (Thank you Sushanth)
See it Here
Also @RyanKinal make a good point in his comment "jQuery may not even normalize colors to a specific format, so different browsers may return colors in different formats. It's something to be aware of." I've not tested ...
CSS "red" as returned via different browsers:
- Firefox 17: "rgb(255, 0, 0)"
- Chrome 24: "rgb(255, 0, 0)"
- Opera 12: "rgb(255, 0, 0)"
- Safari 5: "rgb(255, 0, 0)"
- IE 7-9: "red"
来源:https://stackoverflow.com/questions/13687963/jquery-beginner-change-background-on-click