Add class to element when scrolled into view (scrollable div)

后端 未结 3 1513
滥情空心
滥情空心 2020-12-11 21:01

Is there a solution for adding a class to the element in view when scrolling, and removing when out of view? This needs to work for a scrollable div. I have found a few solu

3条回答
  •  醉梦人生
    2020-12-11 21:55

    You could make your own jQuery plugin to do this. Something like this which takes two functions (whenInView, whenNotInView):

    $('.journal-slider .each-slide img').inViewport(
        function(){$(this).addClass("am-in-view");},
        function(){$(this).removeClass("am-in-view");}
    );
    

    It tests on scroll (or resize) wether the target elements are currently within the viewport and calls the related function.

    Here's the whole thing as a demo Snippet. In this example I have added an animation to the .am-in-view class so that you can see it working as the elements enter the viewport. This has not been tested on anything other than Chrome so far. Feel free to use and improve.

    /*! inViewport 0.0.1 
     *  jQuery plugin by Moob
     * ======================== 
     *  (requires jQuery) 
     */  
    (function ($) {
    
        var vph=0;
        function getViewportDimensions(){
            vph = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
        }
        getViewportDimensions();    
        //on resize/scroll
        $(window).on('resize orientationChanged', function(){
            getViewportDimensions();
        });            
        
        $.fn.inViewport = function (whenInView, whenNotInView) {                  
            return this.each(function () {
                var el = $(this),
                    inviewalreadycalled = false,
                    notinviewalreadycalled = false;                            
                //on resize/scroll
                $(window).on('resize orientationChanged scroll', function(){
                    checkInView();
                });               
                function checkInView(){
                    var rect = el[0].getBoundingClientRect(),
                        t = rect.top,
                        b = rect.bottom;
                    if(t0){
                        if(!inviewalreadycalled){
                            whenInView.call(el);
                            inviewalreadycalled = true;
                            notinviewalreadycalled = false;
                        }
                    } else {
                        if(!notinviewalreadycalled){
                            whenNotInView.call(el);
                            notinviewalreadycalled = true;
                            inviewalreadycalled = false;
                        }
                    }
                }
                //initial check
                checkInView();                
            });
        }             
    }(jQuery));
    html, body {
        margin:0;
    }
    .me, .not-me {
        padding:20px;
        border:1px solid #aaa;
        margin:20px;
    }
    .am-in-view {
        background-color:pink;
        -webkit-transition: all 1500ms;
        -moz-transition: all 1500ms;
        -o-transition: all 1500ms;
        transition: all 1500ms;
    }
    
    

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eveniet, pariatur.

    Saepe, eligendi nihil totam dolorum reprehenderit! Repellat omnis neque quasi.

    Eos cumque voluptatum placeat eius nisi facere neque nesciunt praesentium.

    Eos qui consectetur voluptatem eum, labore accusamus tempora distinctio sunt?

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi, sit.

    A veritatis quis quae totam accusamus repellendus adipisci corporis soluta.

    Debitis animi dolor distinctio ratione dolorum ex aperiam maiores fugit?

    Incidunt non consequatur porro provident recusandae sunt architecto repellat enim.

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis, reprehenderit?

    Neque tempora perferendis dolor, mollitia debitis sunt voluptas ea ut!

    Maiores earum officia corporis, sint voluptatem, in laboriosam perferendis asperiores?

    Odit dolor voluptate laboriosam voluptatem accusamus aperiam explicabo at provident.

    I'm totally normal

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ullam, accusamus.

    Quisquam architecto repellat facere amet sapiente dolore obcaecati harum fuga.

    Tempora labore, unde necessitatibus ipsam repellat architecto, aliquam autem at.

    Sapiente quis doloremque a illum, repellat, eius corporis ab placeat.

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate, assumenda!

    Nesciunt corrupti, eaque dolores ut libero ipsam dolorem laudantium saepe.

    Similique quisquam quod esse expedita, voluptate quia nobis? Cum, tempore.

    Amet voluptatem eaque non, praesentium tenetur molestias minima architecto laboriosam?

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore, ex?

    Perferendis hic, sint maxime similique quia autem cum quasi? Sed.

    Nemo ratione aliquid itaque est blanditiis aliquam maiores veniam ab!

    Reiciendis cumque fugit earum ea animi et aut molestiae dolores!

提交回复
热议问题