如何判断DOM元素在当前视口中是否可见? [英] How can I tell if a DOM element is visible in the current viewport?

查看:202
本文介绍了如何判断DOM元素在当前视口中是否可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种有效的方法来判断DOM元素(在HTML文档中)当前是否可见(显示在视口中)?

Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the viewport)?

(问题涉及Firefox。)

(The question refers to Firefox.)

推荐答案

更新:我们的浏览器。 不再推荐使用此技术,您应该使用 Dan的解决方案,如果您不需要在7之前支持Internet Explorer版本。

Update: Time marches on and so have our browsers. This technique is no longer recommended and you should use Dan's solution if you do not need to support version of Internet Explorer before 7.

原始解决方案(现已过时):

这将检查元素在当前视口中是否完全可见:

This will check if the element is entirely visible in the current viewport:

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

您可以修改此内容,只是确定元素的任何部分在

You could modify this simply to determine if any part of the element is visible in the viewport:

function elementInViewport2(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 + window.innerHeight) &&
    left < (window.pageXOffset + window.innerWidth) &&
    (top + height) > window.pageYOffset &&
    (left + width) > window.pageXOffset
  );
}

这篇关于如何判断DOM元素在当前视口中是否可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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