JavaScript scroll wheel event
IE6.0 first realized the scroll wheel event of the mouse, and its good interaction effect was recognized. Then mainstream browsers such as Opera, chrome, and safari all achieved this effect, however, there are a lot of compatibility issues.
Most browsers support mousewheel event operations, which can be triggered on any element and eventually bubble to the document or window object. In Firefox, DOMMouseScroll supports another event, the most special one is that it must be implemented using the addEventListener method.
1 // set the triggered function to fn
2 if (oDiv. addEventListener ){
3 oDiv. addEventListener ('dommousescroll ', fn, false );
4}
5 oDiv. onmousewheel = fn;
The mousewheel trigger event has a special event attribute -- wheelDelta. When you scroll forward, its value is a multiple of 120. When you scroll backward, its value is a multiple of-120. However, in versions earlier than Opera9.5, the positive and negative numbers are reversed. In Firefox, there is no wheelDelta attribute, but the detail attribute. Compared with wheelDelta, it not only reverses the positive and negative numbers, the value is a multiple of 3. You can set a Boolean value to solve the problem of compatibility with positive and negative numbers.
// This is a function that uses the scroll wheel to change the div height.
Function fn (ev ){
Var ev = ev | event;
Var B = true;
If (ev. wheelDelta ){
B = ev. wheelDelta> 0? True: false;
} Else {
B = ev. detail <0? True: false;
}
If (B ){
ODiv. style. height = oDiv. offsetHeight-10 + 'px ';
} Else {
ODiv. style. height = oDiv. offsetHeight + 10 + 'px ';
}
}
In this function, scroll up B to true, scroll down B to false.
However, if the page has a scroll bar, the browser's default event is triggered when the scroll wheel is rolled on the div. Generally, return false is used for processing. In addEventListener, you need to use the preventDefault function to eliminate browser default events.
// Add an operation at the end of the fn function to remove default browser events
If (ev. preventDefault ){
Ev. preventDefault ();
}
Return false;
The above can solve most of the compatibility problems caused by the scroll wheel event.
This article permanently updates link: https://www.bkjia.com/Linux/2018-03/151410.htm