我正在尝试使用下面的代码为sprite设置动画,但是在进入循环的下一次迭代之前不是等待大约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;
答案 0 :(得分: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 ++;
};
&#13;
div {
height: 317px;
width: 50px;
display: inline-block;
background: url(https://pbs.twimg.com/profile_images/2186972673/super_mario.jpg);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ad_1"></div>
&#13;
答案 1 :(得分:1)
取出循环的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;
}
}