I'm trying to set background-image
property of one element, depending on value of variable. It works only the first time. When I switch to ready, background image stops changing. Images themselves are small - around 8-10 kB.
This is my code:
if(status != '') {
console.log('status');
console.log(status);
switch(status) {
case 'dev':
$('#status').css('background-position','0px -160px');
break;
case 'ready':
$('#status').css('background-position','0px -240px');
break;
case 'soon':
$('#status').css('background-position','0px 0px');
break;
case 'design':
$('#status').css('background-position','0px -80px');
break;
}
}
And here come CSS for the element:
#status {
z-index: 1;
float: right;
height: 80px;
width: 80px;
background: url(/images/front/status-sprite.png);
background-position: 0px -160px;
margin: 0 10px 0 0;
}
Behavior didn't change. A background image does changes to ready, but doesn't change back.
EDIT: Code is updated using sprites generated by csssprites.com.
Your code seems fine, I'd suggest validating that the path exists to each image, you're trying to display. (although if the path is correct, you could override the stylesheet with the !important
tag)
Fiddles
Although it doesn't matter it isn't necessary to surround the url()
on the background-image
property with double quotations
.
$('#status').css('background-image','url(/images/front/status-design.png)');
来源:https://stackoverflow.com/questions/15944127/setting-background-image-using-jquery-changes-background-only-once