2016-11-20 3 views
0

Ich versuche, ein Sprite mit dem unten stehenden Code zu animieren, aber anstatt etwa 1 Sekunde vor der nächsten Iteration der Schleife zu warten, scheint die Animation vom ersten Bild im Sprite zu springen der letzte innerhalb von etwa einer Sekunde. Kann mir jemand sagen, wie ich den Code ändern könnte, damit er so funktioniert, wie ich es mir vorstelle? Vielen Dank!setInterval für css Sprite Animation

preview = setInterval(animation,1000); 
counter = 0; 

function animation() { 
    while (counter < 81){ 
     position = counter * 1.25; 
     $('#ad_1').css({"background-position" : position + "% 0%"}); 
     counter ++; 
    } 
}; 

preview; 

Antwort

1

Nehmen Sie die während Teil der Schleife aus.

function animation() { 
    if (counter < 81){ 
     position = counter * 1.25; 
     $('#ad_1').css({"background-position" : position + "% 0%"}); 
     counter ++; 
    } else { 
     clearInterval(preview); /* this will stop the interval timer, since you won't need it after 80 repetitions. */ 
     preview = null; 
    } 
} 
2

Ihre while-Schleife bewirkt, dass beim ersten Intervallaufruf alles passiert. Entfernen Sie es, und Sie werden nur auf Intervalle in Abhängigkeit:

preview = setInterval(animation,1000); 
counter = 0; 

function animation() { 
     position = counter * 1.25; 
     $('#ad_1').css({"background-position" : position + "% 0%"}); 
     counter ++;   
}; 

preview; 

anschauliches Beispiel:

var preview = setInterval(animation,100); 
 
var counter = 0; 
 

 
function animation() { 
 
     position = counter * 1.25; 
 
     $('#ad_1').css({"background-position" : position + "% 0%"}); 
 
     counter ++;   
 
};
div { 
 
    height: 317px; 
 
    width: 50px; 
 
    display: inline-block; 
 
    background: url(https://pbs.twimg.com/profile_images/2186972673/super_mario.jpg); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="ad_1"></div>