如何检查元素是否在屏幕外 [英] How to check if an element is off-screen

查看:102
本文介绍了如何检查元素是否在屏幕外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用jQuery检查DIV元素是否未脱离屏幕.元素是可见的,并根据CSS属性显示,但是可以通过以下方式有意地将其放置在屏幕外:

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 placed off-screen by:

position: absolute; 
left: -1000px; 
top: -1000px;

我不能使用jQuery :visible选择器,因为元素的高度和宽度不为零.

I could not use the jQuery :visible selector as the element has a non-zero height and width.

我什么都没做.这种绝对位置放置是我的 Ajax 框架实现某些小部件的隐藏/显示的方式.

I am not doing anything fancy. This absolute position placement is the way my Ajax framework implements the hide/show of some widgets.

推荐答案

取决于您对屏幕外"的定义.是在视口内还是在页面的定义边界内?

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

使用 Element.getBoundingClientRect(),您可以轻松地检测是否您的元素位于视口的边界内(即屏幕上或屏幕外):

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');

这篇关于如何检查元素是否在屏幕外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆