JQuery过渡动画

时间:2014-08-24 01:36:34

标签: javascript jquery animation setinterval

此程序从json-object Employees数组中随机选择两名员工,winnerPos已定义。

为了获得更好的用户体验,我将这些功能编程为逐个更改图片。当随机选择的人显示在屏幕上时,动画停止。

按下slideThrough按钮时会触发start功能。

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

问题是动画不能顺利运行。起初它有效但不完美。第二次转换以不规则的方式发生,即不同的速度和fadeIn / fadeOut因图片而异。

有人可以帮助我微调过渡吗?

1 个答案:

答案 0 :(得分:1)

我会避免使用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();

jsfiddle