Call Scroll only when user scrolls, not when animate()

后端 未结 3 479
清酒与你
清酒与你 2020-12-03 16:32

I have a few links across the page with the purpose of \"going to the top\", accomplished by scrolling the page to the top with a nice animation. I\'ve noticed that sometime

3条回答
  •  [愿得一人]
    2020-12-03 16:47

    I was with the same problem, but I found a solution right on jQuery Documentation. There is a property in animate method that lets you set a callback function when animation is completed.

    http://api.jquery.com/animate/#animate-properties-duration-easing-complete

    Here is the code:

    $('#gototop').click(function() {
    
        //This will help you to check 
        var animationIsFinished = false;
    
        $('body').animate({scrollTop:0},3000,"swing",function(){
    
            //this function is called when animation is completed
            animationIsFinished = true;
    
        });
        $(window).scroll(function () {
            //Check if animation is completed
            if ( !animationIsFinished ){
                $('body').stop();
            }
        });
        return false;
    })
    

提交回复
热议问题