jQuery 滚动淡入崩溃



这段代码运行良好,但是当我在 4-5 次后上下滚动时,它崩溃了,所有元素都消失了。为什么会发生这种情况,我该如何解决?

$(window).on("load",function() {
    $(window).scroll(function() {
        var winheight = $(window).innerHeight();
            $(".fade").each(function() {
                /* Check the location of each desired element */
                var objectBottom = $(this).offset().top + $(this).outerHeight();
                var windowBottom = $(window).scrollTop() + $(window).innerHeight();
                /* If the element is completely within bounds of the window, fade it in */
                if ( windowBottom > (objectBottom - (winheight*0.65))) { //object comes into view (scrolling down)
                    if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}
                } else { //object goes out of view (scrolling up)
                    if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}
                }
            });
        }); $(window).scroll(); //invoke scroll-handler on page-load
    });

好的,我假设你的 html 是这样的:https://jsfiddle.net/szdwwdac/

有时,如果你上下快速滚动,当元素淡出时,你的 if 不能很好地工作。

if ( windowBottom >= (objectBottom - (winheight*0.65))) { 
       if ($(this).css("opacity")==0) {$(this).fadeTo(300,1);}
} else { //object goes out of view (scrolling up)
       if ($(this).css("opacity")==1) {$(this).fadeTo(300,0);}
}

这是因为500毫秒的动画。解决方案之一可以是滚动页面的 500 毫秒的 eneble/禁用。您可以查看此解决方案: 如何暂时禁用滚动?

编辑

另一种解决方案可以是:当你在if内时添加一个类"淡入淡出"。然后,在 if 中,如果元素具有类"褪色",则 eval 。如果没有,您可以进入内部制作动画。

最新更新