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

前端 未结 6 747
孤街浪徒
孤街浪徒 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:38

    To check if an element is in the current veiwport:

    function elementInViewport(el) {
      var top = el.offsetTop;
      var left = el.offsetLeft;
      var width = el.offsetWidth;
      var height = el.offsetHeight;
    
      while(el.offsetParent) {
        el = el.offsetParent;
        top += el.offsetTop;
        left += el.offsetLeft;
      }
    
      return (
        top >= window.pageYOffset &&
        left >= window.pageXOffset &&
        (top + height) <= (window.pageYOffset + window.innerHeight) &&
        (left + width) <= (window.pageXOffset + window.innerWidth)
      );
    }
    

    (Source)

    For a more robust method, I'd recommend Viewport Selectors, which allow you to just do:

    $("#elem:in-viewport")
    

提交回复
热议问题