Detect when elements within a scrollable div are out of view

前端 未结 8 1833
我寻月下人不归
我寻月下人不归 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:37

    Here's a pure javascript version of the accepted answer without relying on jQuery and with some fixes to the partial in view detection and support for out of view on top.

    function checkInView(container, element, partial) {
    
        //Get container properties
        let cTop = container.scrollTop;
        let cBottom = cTop + container.clientHeight;
    
        //Get element properties
        let eTop = element.offsetTop;
        let eBottom = eTop + element.clientHeight;
    
        //Check if in view    
        let isTotal = (eTop >= cTop && eBottom <= cBottom);
        let isPartial = partial && (
          (eTop < cTop && eBottom > cTop) ||
          (eBottom > cBottom && eTop < cBottom)
        );
    
        //Return outcome
        return  (isTotal  || isPartial);
    }
    

    And as a bonus, this function ensures the element is in view if it's not (partial or full):

    function ensureInView(container, element) {
    
        //Determine container top and bottom
        let cTop = container.scrollTop;
        let cBottom = cTop + container.clientHeight;
    
        //Determine element top and bottom
        let eTop = element.offsetTop;
        let eBottom = eTop + element.clientHeight;
    
        //Check if out of view
        if (eTop < cTop) {
          container.scrollTop -= (cTop - eTop);
        }
        else if (eBottom > cBottom) {
          container.scrollTop += (eBottom - cBottom);
        }
    }
    

提交回复
热议问题