问题描述
是否有一种有效的方法可以判断 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 的解决方案 如果您不需要支持 Internet Explorer 7 之前的版本.
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 元素在当前视口中是否可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!