2016-11-20 83 views
0

我想要使用下面的代码来动画一个精灵,但不是等待大约1秒钟,然后才能进入下一个迭代循环,动画似乎从精灵中的第一个图像跳转到最后一秒钟内。任何人都可以告诉我,我可以如何改变代码,使其按我想到的方式工作?谢谢!css sprite动画的setInterval

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

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

preview; 

回答

1

搭袢出来的,而部分。

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

您的while循环导致在第一次间隔调用中发生的一切。 删除它,你会只在间隔取决于:

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

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

preview; 

活生生的例子:

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>