jQuery div 向下滚动时滑入,向上滚动时滑出

jQuery div Slide in on scrolldown, slide out on scrollup

这让我可以将 #contact div 滑入,但是当我向上滚动时它不会滑出。

$(window).scroll(function(){
    if ($(this).scrollTop() > 100) {
        $('#scrolltop').fadeIn();
        $('#contact').animate({
            right: "0px"
        }, 500 );
    } else {
        $('#scrolltop').fadeOut();
        $('#contact').animate({
           right: "-115px"
        }, 500 );
    }
});

当用户滚动时,scroll 事件被触发多次,而在您的代码中,animate 函数被快速连续调用多次,这似乎导致了问题。我建议添加一个标志以确定您是否已经调用了 animate。此代码对我有用:

var animated = false;
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
    if(!animated){
        $('#scrolltop').fadeIn();
        $('#contact').animate({
            left: 0
        }, 500 );
        animated = true;
    }
} else if(animated){
    $('#scrolltop').fadeOut();
    $('#contact').animate({
       left: -115
    }, 500 );
    animated = false;
}

编辑:

为了解决用户快速上下滚动时重复调用多次动画的问题,我会另外跟踪元素当前是否正在动画,如下所示:

    var animated = false;
    var animating = false;
    $(window).scroll(scroll);

    function scroll(){
        if(!animating) {
            if ($(document).scrollTop() > 100) {
                    if(!animated){
                    animating = true;
                        $('#scrolltop').fadeIn();
                        $('#contact').animate({
                                left: 0
                        }, {"duration":500,"complete":complete});
                        animated = true;
                    }
            } else if(animated){
                animating = true;
                    $('#scrolltop').fadeOut();
                    $('#contact').animate({
                        left: -115
                    }, {"duration":500,"complete":complete} );
                    animated = false;
            }
        }
    }

    function complete(){
        animating = false;
        scroll();
    }

在此代码中,animated 显示元素是否滑入或滑出屏幕,而 animating 显示当前是否正在使用动画(进或出)。我建议这样做而不是尝试使用超时。