该程序从 json-object Employees
数组中随机选择两名员工,winnerPos
已定义。
为了更好的用户体验,我编写了这些功能来一张一张地更换图片。当随机选择的人出现在屏幕上时,动画停止。
按下start
按钮时将触发slideThrough
函数。
function slideThrough() {
counter = 0;
start = true;
clearInterval(picInterval);
picInterval = setInterval(function () {
changePicture();
}, 500);
}
function changePicture() {
if (start) {
if (counter > winnerPos) {
setWinner();
start = false;
killInterval();
} else {
var employee = Employees[counter];
winnerPic.fadeOut(200, function () {
this.src = 'img/' + employee.image;
winnerName.html(employee.name);
$(this).fadeIn(300);
});
counter++;
}
}
}
问题是动画运行不流畅。起初它可以工作,但并不完美。第二次过渡以不规则的方式发生,即不同的速度和淡入/淡出因图片而异。
有人可以帮我微调过渡吗?
最佳答案
我会避免使用 setInterval()
并在对 .fadeIn()
的调用中添加一个函数来启动下一张图片的动画。
它看起来像这样:
function changePicture(pos) {
pos = pos || 0;
if (pos <= winnerPos) {
var employee = Employees[pos];
winnerPic.fadeOut(200, function() {
this.src = 'img/' + employee.image;
winnerName.html(employee.name);
$(this).fadeIn(300, function() {
changePicture(pos + 1);
});
});
} else {
setWinner();
}
}
要启动动画,您可以调用不带任何参数的 changePicture()
,如下所示。
changePicture();
关于javascript - JQuery 过渡动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25467821/