2013-12-10 98 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);