Detect when elements within a scrollable div are out of view

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

    Based of the best answer. Instead of just telling you if an element is partially visible or not. I added a little extra so you can pass in a percentage (0-100) that tells you if the element is more than x% visible.

    function (container, element, partial) {
        var cTop = container.scrollTop;
        var cBottom = cTop + container.clientHeight;
        var eTop = element.offsetTop;
        var eBottom = eTop + element.clientHeight;
        var isTotal = (eTop >= cTop && eBottom <= cBottom);
        var isPartial;
    
        if (partial === true) {
            isPartial = (eTop < cTop && eBottom > cTop) || (eBottom > cBottom && eTop < cBottom);
        } else if(typeof partial === "number"){
            if (eTop < cTop && eBottom > cTop) {
                isPartial = ((eBottom - cTop) * 100) / element.clientHeight > partial;
            } else if (eBottom > cBottom && eTop < cBottom){ 
                isPartial = ((cBottom - eTop) * 100) / element.clientHeight > partial;
            }
        }
        return (isTotal || isPartial);
    }
    
    0 讨论(0)
  • 2020-12-24 13:50

    I was able to make this work by making a small change to the pure javascript version posted

    function checkInView(container, element, partial) {
    
        //Get container properties
        let cTop = container.scrollTop;
        let cBottom = cTop + container.clientHeight;
    
        //Get element properties
        let eTop = element.offsetTop - container.offsetTop; // change here
        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);
      }
    
    0 讨论(0)
提交回复
热议问题