简体   繁体   English

使用jQuery设置背景图片只会更改背景一次

[英]Setting background-image using jQuery changes background only once

I'm trying to set background-image property of one element, depending on value of variable. 我正在尝试根据变量的值设置一个元素的background-image属性。 It works only the first time. 它只能在第一次使用。 When I switch to ready, background image stops changing. 当我切换到就绪状态时,背景图像停止更改。 Images themselves are small - around 8-10 kB. 图像本身很小-大约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: 这是元素的CSS:

#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 . 编辑 :使用csssprites.com生成的sprite更新代码。

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) (尽管如果路径正确,您可以使用!important标签覆盖样式表)

Fiddles 小提琴

Although it doesn't matter it isn't necessary to surround the url() on the background-image property with double quotations . 尽管没关系,但不必在background-image属性的url()double quotations

$('#status').css('background-image','url(/images/front/status-design.png)');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM