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

后端 未结 3 1506
滥情空心
滥情空心 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:41

    where offset is an element's offset from screen. you should call this (throttles) using the scroll event, the repeatedly check if an element is in view.

    function isElementInViewport(el, offset){
            var rect = el.getBoundingClientRect();
            offset = offset || 0;
    
            return (
                rect.top - offset >= 0 &&
                rect.left >= 0 &&
                rect.bottom + offset <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
            );
     }
    

    using with onscroll event:

    // utilizing underscore's `debounce` method
    $(window).on('scroll.checkVisibility', _.debounce(check, 200));
    
    function check(){
        var visibility = isElementInViewport(element, -100);
        if( visibility )
           // do something if visisble
    
    }
    

提交回复
热议问题