Find element that's on the middle of the visible screen (viewport), on scroll

前端 未结 3 2026
太阳男子
太阳男子 2021-01-02 10:48

I need to know if there is a way I can determine if a div is in the center of the screen.

HTML:

3条回答
  •  余生分开走
    2021-01-02 11:42

    DEMO PAGE

    var findMiddleElement = (function(docElm){
        var viewportHeight = docElm.clientHeight,
            // here i'm using pre-cached DIV elements, but you can use anything you want.
            // Cases where elements are generated dynamically are more CPU intense ofc.
            elements = $('div'); 
    
        return function(e){
            var middleElement;
            if( e && e.type == 'resize' )
                viewportHeight = docElm.clientHeight;
    
            elements.each(function(){
                var pos = this.getBoundingClientRect().top;
                // if an element is more or less in the middle of the viewport
                if( pos > viewportHeight/2.5 && pos < viewportHeight/1.5 ){
                    middleElement = this;
                    return false; // stop iteration 
                }
            });
    
            console.log(middleElement);
        }
    })(document.documentElement);
    
    $(window).on('scroll resize', findMiddleElement);
    

    Another way (for modern browsers only) is to use the intersection API

提交回复
热议问题