How to check if an element is in the view of the user with jquery

前端 未结 6 752
孤街浪徒
孤街浪徒 2020-11-30 04:28

I have a very big draggable div in my window. This div has a smaller window.

6条回答
  •  甜味超标
    2020-11-30 04:41

    For a more up-to-date way using getBoundingClientRect():

    var isInViewport = function (elem) {
        var bounding = elem.getBoundingClientRect();
        return (
            bounding.top >= 0 &&
            bounding.left >= 0 &&
            bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
    };
    

    Returns true if the element in completely in the viewport, and false if it’s not.

    var myElem = document.querySelector('#draggable');
    if (isInViewport(myElem)) {
        // Do something...
    }
    

    Complete explanation found here.

提交回复
热议问题