Setting background-image using jQuery changes background only once

心不动则不痛 提交于 2019-12-08 05:45:43

问题


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.


回答1:


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

  • Background Fiddle
  • Sprite Fiddle

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!