Fade In div when it's scrolled into viewport

后端 未结 3 2049
梦谈多话
梦谈多话 2021-02-13 09:54

Okay, so I\'ve been searching for a simple way to fade in a div when a user scrolls it into view, but I can\'t find a straight solution.

HTML

3条回答
  •  梦毁少年i
    2021-02-13 10:26

    Here's a solution that triggers the fadeIn jQuery function after scrolling by the .topdiv div.

    It subtracts the viewport size from the scrollTop function to get the bottom of the scroll position, and then checks whether its value is greater than the height of the .topdiv div plus the 150px or however far down you'd like it to fadeIn at.

    Since the div must initially be displayed on the page so that we have somewhere to scroll down to we set the visibility to hidden instead of using display:none. We're using fadeIn, which expects the element to start with display:none, so we hide the .fadethisdiv div and fade it in.

    We then remove the scroll listener so that the element doesn't continuously hide and fadeIn after we have scrolled past the .fadethisdiv div.

    $(window).scroll(function () {
        console.log($(window).scrollTop());
        var topDivHeight = $(".topdiv").height();
        var viewPortSize = $(window).height();
    
        var triggerAt = 150;
        var triggerHeight = (topDivHeight - viewPortSize) + triggerAt;
    
        if ($(window).scrollTop() >= triggerHeight) {
            $('.fadethisdiv').css('visibility', 'visible').hide().fadeIn();
            $(this).off('scroll');
        }
    });
    

    Fiddle

提交回复
热议问题