Native JS bound pulley scroll events are compatible with common browsers

  • 2020-03-30 03:28:19
  • OfStack

The pulley scroll page event comes into play in web effects, but it is implemented differently in different browsers. The method I implemented below is compatible with common browsers.


function getData(event){ 
var e = event || window.event; 
//Gets the rolling distance (FF each time the data is 3 or -3, others are 120 or -120)
var data = e.detail || e.wheelDelta; 
alert(data); 
} 

//Binding event methods outside IE
if(document.addEventListener && !document.attachEvent) 
{ 
document.addEventListener('mousewheel',getData); 
//FF binding scroll events
document.addEventListener('DOMMouseScroll',getData); 
} 
//IE 
else if(document.attachEvent && !document.addEventListener){ 
document.attachEvent('onmousewheel',getData); 
}else{ 
window.onmousewheel = getData; 
}

Note in the code:

1 why the use of the document. The addEventListener &&! Document.attachevent to distinguish IE?

AttachEvent and detachEvent are IE specific methods for binding and unbinding events, and only exist in IE. However, a common addEventListener method is implemented in IE9+ to bind events. The browser with the document. The addEventListener method can eliminate not IE8 and the following version, but included the Internet explorer 9 + browser, so use && behind! Document.attachevent 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 it is also worth noting that when using addEventListener to bind an event, the event name is not preceded by an on, and when using attachEvent to bind an event in IE, an on is required.


Related articles: