Home >Web Front-end >JS Tutorial >JavaScript wheel event usage instructions_javascript skills

JavaScript wheel event usage instructions_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:33:001063browse

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:

Copy code The code is as follows:

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:
Copy the code The code is as follows:

/**
* 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:
Copy code The code is as follows:

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);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn