How to check if an element is off-screen

后端 未结 7 1838
太阳男子
太阳男子 2020-11-27 11:39

I need to check with jQuery if a DIV element is not falling off-screen. The elements are visible and displayed according CSS attributes, but they could be intentionally plac

7条回答
  •  心在旅途
    2020-11-27 12:10

    Depends on what your definition of "offscreen" is. Is that within the viewport, or within the defined boundaries of your page?

    Using Element.getBoundingClientRect() you can easily detect whether or not your element is within the boundries of your viewport (i.e. onscreen or offscreen):

    jQuery.expr.filters.offscreen = function(el) {
      var rect = el.getBoundingClientRect();
      return (
               (rect.x + rect.width) < 0 
                 || (rect.y + rect.height) < 0
                 || (rect.x > window.innerWidth || rect.y > window.innerHeight)
             );
    };
    

    You could then use that in several ways:

    // returns all elements that are offscreen
    $(':offscreen');
    
    // boolean returned if element is offscreen
    $('div').is(':offscreen');
    

提交回复
热议问题