css 精灵动画的 setInterval

setInterval for css sprite animation

我正在尝试使用以下代码为精灵制作动画,但在进入循环的下一次迭代之前没有等待大约 1 秒,动画似乎从精灵中的第一张图像跳到最后一张大约一秒钟。任何人都可以告诉我如何更改代码以使其按照我的想法工作吗?谢谢!

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

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

preview; 

您的 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>

去掉循环的 while 部分。

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;
    }
}