Unfortunately, all browsers are different.
1) The event names are different
The corresponding event name for IE, KHTML (Safari, Chrome), and Opera is "mousewheel". The event name corresponding to Gecko (Firefox, Netscape) is "DOMMouseScroll".
2) The properties of event objects are different
Sometimes we need to know whether the user has scrolled up or down. For example, we have a function that responds to scroll events:
function wheelHandle (e) {
if(e.wheelDelta) {// IE, KHTML, Opera
alert(e.wheelDelta > 0 ? 'Scroll up' : 'Scroll down');
} else { // Gecko
alert(e.detail < 0 ? 'Scroll up' : 'Scroll down');
}
}
IE, KHTML supports e .wheelDelta, greater than 0 means scrolling up, less than 0 means scrolling down. Gecko supports e.detail. If it is less than 0, it will scroll up. If it is greater than 0, it will scroll up. It is the opposite of the previous one. Opera, on the other hand, is awesome and supports both.
The following is a function for registering wheel events for reference:
/**
* Register wheel event function
* @param element: Registered event object
* @param wheelHandle: Register event function
*/
function addScrollListener(element, wheelHandle) {
if(typeof element != 'object') return;
if(typeof wheelHandle != 'function') return;
// Monitor browser
if(typeof arguments.callee.browser == 'undefined') {
var user = navigator.userAgent;
var b = {};
b.opera = user.indexOf("Opera") > -1 && typeof window.opera == "object";
b.khtml = (user.indexOf("KHTML") > -1 || user .indexOf("AppleWebKit") > -1 || user.indexOf("Konqueror") > -1) && !b.opera;
b.ie = user.indexOf("MSIE") > - 1 && !b.opera;
b.gecko = user.indexOf("Gecko") > -1 && !b.khtml;
arguments.callee.browser = b;
}
if(element == window)
element = document;
if(arguments.callee.browser.ie)
element.attachEvent('onmousewheel', wheelHandle);
else
element. addEventListener(arguments.callee.browser.gecko ? 'DOMMouseScroll' : 'mousewheel', wheelHandle, false);
}
Register a listening event:
var display = document.getElementById('display');
function wheelHandle(e) {
if(e.wheelDelta) {// IE, KHTML, Opera
display.innerHTML = (e.wheelDelta > 0 ? 'Up' : 'Down');
} else { // Gecko
display.innerHTML = (e.detail < 0 ? 'Up' : 'Down');
}
}
addScrollListener(window, wheelHandle);