简体   繁体   English

禁用滚动滚动以防止浏览器重画

[英]Disable hover on scroll to prevent browser repaint

I have a hover effect on a list of div, the css is: 我在div列表上有一个悬停效果,css是:

.product:hover {
  background-color: #f6f6f7;
  border-left-color: #f6f6f7 !important;
  border-right-color: #f6f6f7 !important;
  outline: 10px solid #f6f6f7;
  z-index: 1;
}

I want this hover effect to not be triggered when the user is scrolling the page, to not force the browser to repaint/reflow. 我希望在用户滚动页面时不触发此悬停效果,以免强制浏览器重新绘制/重排。

So I tried: 所以我尝试了:

doc = $(document)
doc.scroll(->
  $('.product').unbind('mouseenter').unbind('mouseleave')
)

But it doesn't seem to work, when I scroll the hover effect is still triggered. 但这似乎不起作用,当我滚动时,仍会触发悬停效果。 Any idea why? 知道为什么吗? Or how I have achieve that? 或者我是如何实现的?

Add this in your css style page 在您的CSS样式页面中添加此内容

.disable-hover { pointer-events: none; }

You have to do is add the .disable-hover class to the body when you begin to scroll. 您要做的就是在开始滚动时将.disable-hover类添加到主体。 This then allows the users cursor to pass through the body and thus disable any hover effects. 然后,这将允许用户光标穿过身体,从而禁用任何悬停效果。

var body = document.body,timer;
window.addEventListener('scroll', function() {
   clearTimeout(timer);
  if(!body.classList.contains('disable-hover')) {
    body.classList.add('disable-hover')
  }
   timer = setTimeout(function(){
    body.classList.remove('disable-hover')
  },500);
}, false);

Add this script and execute it will works:- 添加此脚本并执行它将起作用:

CSS hover has nothing to do with JavaScript events. CSS悬停与JavaScript事件无关。

If you want to do what you are after, you will need to do it by adding/removing a class onscroll 如果您想做自己想做的事,则需要通过在课堂上添加/删除类来做到这一点

var scrollTimer;
$(window).on("scroll", function() {
    if(scrollTimer) window.clearTimeout(scrollTimer);
    $("body").removeClass("effect");
    scrollTimer = window.setTimeout( function()
        $("body").removeClass("effect");
    }, 100);
});

and the CSS 和CSS

.effect .product:hover {
  background-color: #f6f6f7;
  border-left-color: #f6f6f7 !important;
  border-right-color: #f6f6f7 !important;
  outline: 10px solid #f6f6f7;
  z-index: 1;
}

and PS: using important is BAD practice 和PS:重要的是不良实践

Try setting 尝试设定

document.body.style.pointerEvents = 'none';

when scroll event is triggered. 触发滚动事件时。 Detailed docs here . 详细文档在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM