我试图在滚动时检查元素是否在我的视口(viewport)内。 如果它在我的视口(viewport)之外,我会添加一个类来将元素固定到顶部。
我用来确定元素是否在视口(viewport)之外的函数是:
isElementInViewport : function(el) {
//special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
我添加了一个触发此函数的滚动事件:
$(window).on('scroll', function(event){
testObject.isElementInViewport(event.target);
}
<小时/>
这里的问题是,在滚动时,我的 Lenovo Yoga 的 CPU 变得疯狂。 我尝试过:
轮询
,间隔一定时间- 使用
超时函数
和事件函数范围之外的变量
在特定时间间隔内进行切换
这两种方法都有效,但我需要一种方法来最大限度地减少性能影响,因为我使用它的页面已经有大量 JS 正在工作。 我还需要在栏到达视口(viewport)之外时立即将其固定到顶部,而不是几毫秒后。
是否有任何低性能的解决方案? 这只能在 CSS 中完成吗?
编辑
我注意到我没有问正确的问题。 下面的当前答案是有效的,但是当我向上和向下滚动一点时,也会产生同样巨大的性能影响:
我需要防止脚本需要如此多的 CPU 资源!
最佳答案
复制自jQuery – test if element is in viewport (visible on screen)
HTML
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box orange"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
JQuery
$.fn.isOnScreen = function() {
var win = $(window);
var viewport = {
top: win.scrollTop(),
left: win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
$(window).scroll(function() {
if ($('.orange').isOnScreen() === true) {
console.log("Element is in viewport")
}
});
<强> Fidde
关于javascript - 哪个事件来检查元素是否在滚动时位于视口(viewport)之外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37024487/