Detect when elements within a scrollable div are out of view

前端 未结 8 1826
我寻月下人不归
我寻月下人不归 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);
    }
    

提交回复
热议问题