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
445 views
in Technique[技术] by (71.8m points)

events - mousewheel,wheel and DOMMouseScroll in JavaScript

DOMMouseScroll only works for Firefox.

wheel seems to work for both Firefox and chrome. What is this? Haven't found docs on this one.

mousewheel doesn't work for Firefox.

How should I use them, in order to gain best browser-compatibility.

Example given:

document.addEventListener('ScrollEvent', function(e){
   DoSomething();
});
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I would suggest that all three of them be used at the same time to cover all browsers.

Notes:

  1. In versions of Firefox where both the wheel and DOMMouseScroll events are supported, we need a way to instruct the browser to execute only wheel and not both. Something like the following:if ("onwheel" in window) ...

  2. The above check though, in the case of IE9 and IE10 will fail, because even though these browsers support the wheel event, they don't have the onwheel attribute in DOM elements. To counter that we can use a flag as shown later on.

  3. I believe the number returned by e.deltaY, e.wheelDelta and e.detail is not useful other than helping us determine the direction of the scroll, so in the solution below -1 and 1 will be returned.

Snippet:

/* The flag that determines whether the wheel event is supported. */
var supportsWheel = false;

/* The function that will run when the events are triggered. */
function DoSomething (e) {
  /* Check whether the wheel event is supported. */
  if (e.type == "wheel") supportsWheel = true;
  else if (supportsWheel) return;

  /* Determine the direction of the scroll (< 0 → up, > 0 → down). */
  var delta = ((e.deltaY || -e.wheelDelta || e.detail) >> 10) || 1;

  /* ... */
  console.log(delta);
}

/* Add the event listeners for each event. */
document.addEventListener('wheel', DoSomething);
document.addEventListener('mousewheel', DoSomething);
document.addEventListener('DOMMouseScroll', DoSomething);

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

...