javascript - 哪个事件来检查元素是否在滚动时位于视口(viewport)之外?

标签 javascript jquery css

我试图在滚动时检查元素是否在我的视口(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 中完成吗?

编辑

我注意到我没有问正确的问题。 下面的当前答案是有效的,但是当我向上和向下滚动一点时,也会产生同样巨大的性能影响:

First answer Second answer

我需要防止脚本需要如此多的 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/

相关文章:

javascript - 如何在正则表达式中创建或运算符?

javascript - 在 Javascript 字符串中查找 <img> 标签的 src 属性值

javascript - 增加一个 div 数据值,然后在 coffeescript 中再次设置它

html - flex-direction 列属性不起作用

c# - 如何将标签值作为参数传入 javascript 函数?

asp.net - 如何在子页面的onload事件中调用javascript

javascript - 辅助功能:在密码输入中显示/隐藏密码按钮

jquery - 平滑滚动冲突 css3

javascript - DataTables 1.9.4 禁用特定行的排序

javascript - css/背景大小在 chrome 中不起作用