定时器只运行一次后的jQuery动画

时间:2013-03-05 17:58:14

标签: javascript jquery animation

我正在进行基于网络的测验,我希望每次我的计时器栏宽度设置为0时都会触发leftScroll jQuery动画。 然而,它只在第一次工作。我知道这是因为它总是针对第一个.qAnswers a我如何让它每次都开始下一次?

链接:http://www.carlpapworth.com/friday-quiz/#

JS:

timesUp();

function timesUp(){
            $('#timerBar').animate({'width':'0px'}, 1500, function(){
                nextQuestion(function(){
                    resetTimer();
                }); 
            });                 
}

function nextQuestion(event){
    var $anchor = $('.qAnswers a');
     $('#qWrap').stop(true, true).animate({
        scrollLeft: $($anchor.attr('href')).position().left
        }, 2000, function(){
            nextCount();
            $anchor = $anchor.next('.qContainer a');
        });  

}

function resetTimer(){
    $('#timerBar').css('width', '99%');
    timesUp();
}

点击“回答”时,我正在使用这个JS来触发动画:

$('.qAnswers li a').bind('click',function(event){
                    $(this).parent().addClass('selected');
                        var $anchor = $(this);
                        $('#qWrap').stop(true, true).delay(800).animate({
                            scrollLeft: $($anchor.attr('href')).position().left
                        }, 2000, function(){
                nextCount();
                        });
                        stopTimer();
                        event.preventDefault();
                    });

2 个答案:

答案 0 :(得分:0)

Try this simplified fiddle

问题在于:

nextQuestion(function(){
    resetTimer();
 }); 

您无法将回调函数传递给nextQuestion。我猜你想在显示nextQuestion时重置计时器。

如果是这种情况,只需将resetTimer()放入animate()

的调用函数中

以下是代码,您需要对其进行调整。

timesUp();

function timesUp() {
    $('#timerBar').animate({
        'width': '0px'
    }, 5000, function () {
        nextQuestion();

    });
}

function nextQuestion(event) {
    resetTimer();
    /*
    var $anchor = $('.qAnswers a');
    $('#qWrap').stop(true, true).animate({
        scrollLeft: $($anchor.attr('href')).position().left
    }, 2000, function () {
        nextCount();
        resetTimer();
        $anchor = $anchor.next('.qContainer a');
    });
    */

}

function resetTimer() {
    $('#timerBar').css('width', '100%');
    timesUp();
}

答案 1 :(得分:0)

您可以添加计数器以了解要选择的锚点:

var counter = 0;
function nextQuestion(event){
    var $anchor = $('.qAnswers a');

    // try to see the good anchor
    console.log($anchor[counter]);

     $('#qWrap').stop(true, true).animate({
        scrollLeft: $($anchor.attr('href')).position().left
        }, 2000, function(){
            nextCount();
            $anchor = $anchor.next('.qContainer a');
        }); 
     counter ++; 
}