我有一个检查元素是否来自如何判断DOM元素在当前视图中是否可见?的方法。并尝试运行测试以检查元素是否在视图中。
var visibleY = function (el) {
var top = el.getBoundingClientRect().top, rect, el = el.parentNode;
do {
rect = el.getBoundingClientRect();
if (top <= rect.bottom === false) return false;
el = el.parentNode;
} while (el != document.body);
// Check its within the document viewport
return top <= document.documentElement.clientHeight;
};但是,对于低于父元素的客户端高度值的所有元素,它都返回true。做这项工作需要做些什么改变。小提琴
发布于 2014-09-11 05:13:08
如果删除那个问题 cruft (如果您没有一个名为jQuery的全局变量,则会引发错误),下面的回答是有效的:
[deleted code]编辑
基于OP中的链接中的各种答案,下面的内容似乎是可行的,只是轻微的测试,但它在[医]OP小提琴中工作。它检查元素是否在其父级和视图中。希望这些评论是足够的:
// Return true if an element overlaps its parents and the viewport
function isVisible(element) {
return isInParents(element) && isInViewport(element);
}
// Return true if an element overlaps its parents
function isInParents(el) {
var rect = el.getBoundingClientRect(),
rectP,
visible = true;
while (el && el.parentNode && el.parentNode.getBoundingClientRect && visible) {
el = el.parentNode;
rectP = el.getBoundingClientRect();
visible = rectInRect(rectP, rect);
}
return visible;
}
// Return true if element overlaps the viewport
function isInViewport (element) {
var rect = element.getBoundingClientRect();
return rectInRect({top:0, left:0,
bottom: window.innerHeight || document.documentElement.clientHeight,
right: window.innerWidth || document.documentElement.clientWidth
}, rect);
}
// Return true if r1 overlaps r0
function rectInRect(r0, r1) {
return r1.top < r0.bottom &&
r1.bottom > r0.top &&
r1.left < r0.right &&
r1.right > r0.left;
}至于元素是否可见取决于其他因素,如重叠元素是否隐藏,或是否有其他非祖先元素位于顶部等。这些条件可以检查,但越要检查效率越低。
如果彻底性和性能重要,请创建页面上所有元素的空间位置的二叉树索引,并在执行过程中对其进行更新。创建索引是缓慢的,但检查位置将大大加快。
https://stackoverflow.com/questions/25779234
复制相似问题