Mousewheel & dommousescroll event in IE & Edge

夙愿已清 提交于 2019-11-27 06:38:55

问题


I have this code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

<script>
    window.addEventListener('DOMMouseScroll', mouseWheelEvent);
    window.addEventListener('mousewheel', mouseWheelEvent);

    function mouseWheelEvent() {
        alert(1);
    }
</script>
</body>
</html>

It works in Chrome & Firefox. However, it doesn't work with my laptop dell xps 13 9434's touchpad in IE & edge. But it does work with (some) other laptops' touchpads. What to do? jQuery is no problem.

"what doesn't work?" => There is no alert in scroll when using 2 fingers like you use to scroll in browsers.


回答1:


Edit

After some research it seems that the problem is actually Microsoft's.

There is an open issue about it in EdgeHTML issue tracker for almost one year already.

Basically it says that wheel events do not work in Edge (And older IE versions) when using Precision Touchpads.

By the way I dont delete the rest of the answer as it is still relevant. You should use wheel instead anyway.


You should listen to wheel:

window.addEventListener('wheel', mouseWheelEvent);

It has replaced both mousewheel and DOMMouseScroll which are deprecated by now and is supported by all browsers.


Cross browser example:

window.addEventListener('wheel', mouseWheelEvent);   

function mouseWheelEvent() {
    console.log("Fired");
}
<h1>
  Hodor!
</h1>
<h1>
  Hodor!
</h1>
<h1>
  Hodor!
</h1>
<h1>
  Hodor!
</h1>
<h1>
  Hodor!
</h1>
<h1>
  Hodor!
</h1>
<h1>
  Hodor!
</h1>

And JSFiddle demo




回答2:


Some older IE version doesn't support addEventListener, they support attachEvent instead.

Try a crossBrowser addEventListener:

if ( window.attachEvent ) {
 window.attachEvent('on'+eventType, yourHandler); // in your case "scroll"
} else {
 window.addEventListener ...
}

Pay attention to the page height: it won't work if there is no offset. If there is no offset in your page, then use this:

document.attachEvent('onmousewheel', mouseWheelEvent); // the event is attached to document 



回答3:


Staring EdgeHTML 17, Microsoft supports Pointer Events to solve the issue.

https://blogs.windows.com/msedgedev/2017/12/07/better-precision-touchpad-experience-ptp-pointer-events/

As of today, pointer events are supported by all major browsers except Safari:

https://caniuse.com/#search=pointer



来源:https://stackoverflow.com/questions/42012645/mousewheel-dommousescroll-event-in-ie-edge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!