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 Select 器,因为元素的高度和宽度都不是零.

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?

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

Jquery相关问答推荐

为什么如果使用转换规模,juserui可拖动遏制不起作用

try 使用jQuery AJAX将参数传递给http Post方法时出现未知错误

提交表单时运行自定义验证脚本

如何在不使用点击事件 bootstrap 程序模式的情况下使用弹出窗口 bootstrap 程序显示用户详细信息?

jQuery找到最近的匹配元素

Jquery如何通过数组中的属性查找对象

foreach for JSON 数组,语法

如何在 jQuery 中使用:not 和 hasClass() 来获取没有类的特定元素

为什么我们在 jQuery 中使用({ })?

JQuery 数据 Select 器不使用 .data 更新

JavaScript 中的循环计时器

延迟后运行功能

jQuery .hide() 和 .css("display", "none") 的区别

如何使用 jQuery 为文本对齐动态添加样式

从附加元素获取 jQuery 对象的更简单方法

获取元素的底部和右侧位置

如何检测是否安装了 Flash,如果没有,显示一个隐藏的 div 通知用户?

上传文件前验证文件扩展名

如何在 ReactJS 中使用 JQuery

jQuery - 不可见时获取元素的宽度(显示:无)