简体   繁体   中英

Disable hover on scroll to prevent browser repaint

I have a hover effect on a list of div, the css is:

.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

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

You have to do is add the .disable-hover class to the body when you begin to scroll. 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.

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

.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

Try setting

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

when scroll event is triggered. Detailed docs here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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