向下滚动时滑动,向上滚动时滑动

jQuery div Slide in on scrolldown, slide out on scrollup

本文关键字:滚动      更新时间:2023-09-26

这可以让我滑动#contactdiv,但是当我向上滚动时,它不会滑出

$(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;
}
编辑:

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

    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显示当前是否正在使用动画(无论是进入还是退出)。我建议这样做,而不是尝试使用超时。