2013-12-10 95 views
1

我期待创建一个加载精灵,它将在所有浏览器中工作,因为当前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; 
} 

,这里是一个小提琴显示我已经这么远:

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

我有一种感觉,动画由于我设置背景位置的方式存在问题而无法工作 - 以前是否有其他人做过类似的事情? 我已经看过其他的插件,但我希望迄今为止我所需要的几乎都是我需要的,因此我不想包含第三方插件。

+0

你确实意识到浏览器仍然阻止了很多类型的请求,这就是为什么大多数人都仍在使用旧的动画GIF而不是JS动画? – adeneo

+0

是的,此刻我正在使用一个.gif,除了IE以外,它在其他所有方面都运行良好。如果可能的话,我希望能够同时运行一些功能。 – wf4

+0

你想实现什么?我看到一个名为“Wheel”的函数,但没有任何三角函数,所以你所有的点都可以做到最好。你错过了一些分号。也不会做任何事情,它应该是全球性的。 – efkah

回答

1

只是为了好玩,我决定做的这个纯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/

确保keyframesanimation之前插入你喜欢的浏览器前缀。

0

问题来自您如何调用setTimeout。该syntax为setTimeout的是:

var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]); 

在代码的当前版本之前超时被设置,这导致无限递归loadingWheel进行评价。为了有指定的时间后loadingWheel评价,称它是这样的:

setTimeout(loadingWheel, 700, newPos);