jQuery动画后计时器只工作一次

jQuery animation after timer only working once

本文关键字:一次 工作 动画 计时器 jQuery      更新时间:2023-09-26

我正在制作一个基于web的测验,并且我希望每次计时器条宽度设置为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();
                    });

试试这个简化的小提琴

问题在这里:

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

你不能将回调函数传递给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();
}

你可以添加一个计数器来知道选择哪个锚:

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