简体   繁体   English

jQuery div向下滚动,向上滚动

[英]jQuery div Slide in on scrolldown, slide out on scrollup

This lets me slide the #contact div in, but when I scroll up it doesn't slide back out. 这使我可以将#contact div滑入,但是向上滚动时则不会滑出。

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

The scroll event is fired many times when a user scrolls, and with your code, the animate function is called many times in quick succession which seems to be causing problems. 当用户滚动时,滚动事件会被触发很多次,并且在您的代码中,动画函数被快速连续多次调用,这似乎会引起问题。 I would recommend adding a flag to determine if you have already called animate. 我建议添加一个标志以确定您是否已经调用了animate。 This code worked for me: 这段代码对我有用:

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

EDIT: 编辑:

To solve the problem that multiple animate calls are made repeatedly when the user scrolls up and down quickly, I would additionally keep track of whether the element is currently animating, like this: 为了解决当用户快速上下滚动时反复进行多个动画调用的问题,我将另外跟踪该元素当前是否处于动画状态,如下所示:

    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();
    }

In this code, animated shows whether the element has slid in or out of the screen, whereas animating shows whether an animation (either in or out) is currently being used. 在这段代码中, animated显示了元素是滑入还是滑出屏幕,而animating显示了当前是否正在使用动画(入或出)。 I would recommend doing this rather than try and use timeouts. 我建议这样做,而不要尝试使用超时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM