Home > Web Front-end > JS Tutorial > body text

Native JS binding pulley scroll event is compatible with common browsers_javascript skills

WBOY
Release: 2016-05-16 16:42:51
Original
1592 people have browsed it

The event of wheel scrolling is encountered in web page special effects, but the implementation methods are different in different browsers. The method I implemented below is compatible with common browsers.

function getData(event){ 
var e = event || window.event; 
//获取滚动距离(FF每次滚动 data为3或者-3,其他为120或者-120) 
var data = e.detail || e.wheelDelta; 
alert(data); 
} 

//IE之外的绑定事件方法 
if(document.addEventListener && !document.attachEvent) 
{ 
document.addEventListener('mousewheel',getData); 
//FF绑定滚动事件 
document.addEventListener('DOMMouseScroll',getData); 
} 
//IE 
else if(document.attachEvent && !document.addEventListener){ 
document.attachEvent('onmousewheel',getData); 
}else{ 
window.onmousewheel = getData; 
}
Copy after login

Noteworthy places in the code:

1 Why use document.addEventListener && !document.attachEvent to distinguish IE?

attachEvent and detachEvent are IE-specific methods for binding events and unbinding events. This method only exists in IE. However, in the IE9 browser, a more general addEventListener method is implemented to bind events. If there is a document.addEventListener method in the browser, you can exclude versions that are not IE8 and below, but include IE9 browsers, so use &&!document.attachEvent later to exclude IE9 browsers.

2 It is worth noting that there is no mousewheel event in the FF browser, and the time to trigger scrolling is DOMMouseScroll.

3 Another thing worth noting is that when using addEventListener to bind an event, on is not added in front of the event name, but when using attachEvent to bind an event in IE, on is required.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template