How can I determine if an HTML element is offscreen?

↘锁芯ラ 提交于 2019-12-21 17:51:43

问题


How can I determine using jQuery that a given element is above the top of the viewable window area or below the bottom of it? This would allow me to determine whether the item was offscreen and in which direction.

Ideally:

var topPos = $(this).relativeToTop();
var bottomPos = $(this).relativeToBottom();
var isOnScreen = topPos >= 0 && bottomPos >= 0;

Is there a plugin or example online somewhere?


回答1:


var off = $(this).offset();
var t = off.top;
var l = off.left;
var h = $(this).height();
var w = $(this).width();
var docH = $(window).height();
var docW = $(window).width();

var isEntirelyVisible = (t > 0 && l > 0 && t + h < docH && l+ w < docW);

EDIT somewhere in there, it might be an idea to check $(document).scrollTop() as well, depending on how you want the script to deal with scroll state...




回答2:


Thanks David for the post, it helped me solve my 'fully visible element' issue, however I had to tailor the recommendation to the following, because my parent div area was larger than the visible window size. The following code works for me, although I only have to worry about the vertical.

elem is a jquery object, and this will probably only work for html5

function isFullyVisible (elem) {
  var off = elem.offset();
  var et = off.top;
  var el = off.left;
  var eh = elem.height();
  var ew = elem.width();
  var wh = window.innerHeight;
  var ww = window.innerWidth;
  var wx = window.pageXOffset;
  var wy = window.pageYOffset;
  return (et >= wy && el >= wx && et + eh <= wh + wy && el + ew <= ww + wx);  
}


来源:https://stackoverflow.com/questions/1725508/how-can-i-determine-if-an-html-element-is-offscreen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!