jquery - 如何使用背景位置创建加载图像 Sprite

标签 jquery css background-image css-position css-sprites

我希望创建一个加载 Sprite ,它适用于所有浏览器,因为当前 IE 将在调用新页面时停止 .gif 文件中的动画。

到目前为止我有这个功能:

counter = 1;              //how many slides have we seen

function loadingWheel(loc) {
    var img = $('.img_working'),  //this is the div with the sprite
        slideCount = 76,          //this is so that we know when to stop
        slideH = 32,              //this is the height of each frame in the sprite
        pos = loc,                //this is the current y position
        newPos = pos + slideH;    //now we increase the position to set the css


    //set the new css position
    img.css({ 'background-position': 'center -' + newPos + 'px' });

    //Add to the count
    counter++; 

    //if we are the the last slide, we are going to reset the counter
    if (counter == slideCount) {

        //reset the position, wait for 700 ms then go again
        setTimeout(loadingWheel(0), 700);
    }
    else {
        //wait for 700 ms then go again
        setTimeout(loadingWheel(newPos), 700);     
    }  
};

loadingWheel(0);

想法是使用 setTimeout 创建一个循环,该循环将传入当前位置然后增加它,然后再次调用。

到目前为止,HTML 和 CSS 很简单:

<div id="workingMessage">
    <div class="img_working"></div>
</div>

.img_working {
    width:32px;
    height:32px;
    margin:0 auto 20px;
    background: url(http://i.imgur.com/Hwgkxhy.png) top center no-repeat;
}

这是一个 fiddle 来展示我到目前为止所得到的:

http://jsfiddle.net/uLycs/3/

我感觉动画不工作是因为我设置背景位置的方式有问题 - 以前有没有其他人做过类似的事情? 我以前看过其他插件,但我希望到目前为止我所拥有的几乎就是我所需要的,因此我真的不想包含第 3 方插件。

最佳答案

只是为了好玩,我决定为此做一个纯 css 实现。

html:

<div class="img_working"></div>

CSS:

@keyframes scroll-background {
    from {
        background-position: 0% 0%;
    }
    to {
        background-position: 0% 100%;
    }
}

.img_working {
    width:32px;
    height:32px;
    background-image: url(http://i.imgur.com/Hwgkxhy.png);

    animation: scroll-background steps(75, end) infinite 2.4s;
}

http://jsfiddle.net/82h2hbaa/

一定要在关键帧动画之前插入您喜欢的浏览器前缀。

关于jquery - 如何使用背景位置创建加载图像 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20497573/

相关文章:

javascript - 在 $(this) 内按类更改带有 div 的 CSS

jquery - 最简单的脚本像砌 block

jquery - 与 JQuery 的共享点 - 单击列过滤器时停止工作

css - 覆盖 Twitter Bootstrap 样式 - 性能?

html - 将背景图像带到前台。可能与否?

css - 背景颜色超过背景图像

html - 背景图像中的文本溢出

javascript - 滑动菜单不滑动

javascript - 如何调整这个 jQuery 对象的大小?

javascript - 单击单选按钮时动态调整 iFrame 大小