最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Disable hover on scroll to prevent browser repaint - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Jan 26, 2015 at 12:50 Avraam MavridisAvraam Mavridis 8,94022 gold badges87 silver badges135 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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:-

Try setting

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

when scroll event is triggered. Detailed docs here.

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

发布评论

评论列表(0)

  1. 暂无评论