Detect when elements within a scrollable div are out of view

前端 未结 8 1814
我寻月下人不归
我寻月下人不归 2020-12-24 13:15

I need to find a good solution to the following problem. I see a lot of people asking about tracking if an element is in or outside of view Port for the page or browser wind

8条回答
  •  轮回少年
    2020-12-24 13:27

    Here is a pure javascript solution.

    function elementIsVisible(element, container, partial) {
        var contHeight = container.offsetHeight,
        elemTop = offset(element).top - offset(container).top,
        elemBottom = elemTop + element.offsetHeight;
        return (elemTop >= 0 && elemBottom <= contHeight) || 
        (partial && ((elemTop < 0 && elemBottom > 0 ) || (elemTop > 0 && elemTop <= contHeight)))
    }
    
    // checks window
    function isWindow( obj ) {
        return obj != null && obj === obj.window;
    }
    
    // returns corresponding window
    function getWindow( elem ) {
        return isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
    }
    
    // taken from jquery
    // @returns {{top: number, left: number}} 
    function offset( elem ) {
    
        var docElem, win,
            box = { top: 0, left: 0 },
            doc = elem && elem.ownerDocument;
    
        docElem = doc.documentElement;
    
        if ( typeof elem.getBoundingClientRect !== typeof undefined ) {
            box = elem.getBoundingClientRect();
        }
        win = getWindow( doc );
        return {
            top: box.top + win.pageYOffset - docElem.clientTop,
            left: box.left + win.pageXOffset - docElem.clientLeft
        };
    };
    

提交回复
热议问题