Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

javascript - mousewheel e.delta not working right in firefox?

I'm making a single-page website that reacts to mouse wheel events.

    var supportsWheel = false;  
    function DoSomething (e) {
        if (e.type == "wheel") supportsWheel = true;
        else if (supportsWheel) return;
        var delta = ((e.deltaY || -e.wheelDelta || e.detail) >> 10) || 1;
        //if mousewheel is going up
        if (delta > 0) {
            slideDown();
        }
        //if mousewheel is going down
        else if (delta < 0) {
            slideUp();
        }
    }

    document.addEventListener('wheel', DoSomething);
    document.addEventListener('mousewheel', DoSomething);
    document.addEventListener('DOMMouseScroll', DoSomething);

So this works perfectly in chrome and safari but in firefox, both directions of the mouse wheel activate slideDown() function. As opposed to declaring slideUp when the mouse wheel goes up and slideDown when it's going down. Any ideas how to fix it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is because you normalize deltaY = 0 as down, and that you probably have some smooth-scrolling set-up in Firefox, or in your OS:

This smooth scrolling feature will make your delta get linearly smaller, until they reach 0. So, when you initiate a Wheel event from your mouse/scrollpad, it will often end with an event which deltaY will be 0.

You can check this theory with this modified code, which will output the cases where the deltaY is 0 separately.

var supportsWheel = false;

function DoSomething(e) {
  if (e.type == "wheel") supportsWheel = true;
  else if (supportsWheel) return;
  var e_delta = (e.deltaY || -e.wheelDelta || e.detail);
  var delta =  e_delta && ((e_delta >> 10) || 1) || 0;
  if (delta > 0) {
    slideDown();
  } else if (delta < 0) {
    slideUp();
  } else if (!delta) {
    donnotSlide();
  }
}

document.addEventListener('wheel', DoSomething);

function slideDown() {
  console.log('down');
}

function slideUp() {
  console.log('up');
}

function donnotSlide() {
  console.log('was zero');
}
Use your mouse wheel

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...