Javascript:捕获鼠标滚轮事件而不滚动页面? [英] Javascript: Capture mouse wheel event and do not scroll the page?

查看:37
本文介绍了Javascript:捕获鼠标滚轮事件而不滚动页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试防止页面元素捕获的鼠标滚轮事件导致滚动.

I'm trying to prevent a mousewheel event captured by an element of the page to cause scrolling.

我希望 false 作为最后一个参数得到预期的结果,但是在这个画布"元素上使用鼠标滚轮仍然会导致滚动:

I expected false as last parameter to have the expected result, but using the mouse wheel over this "canvas" element still causes scrolling:

this.canvas.addEventListener('mousewheel', function(event) {
   mouseController.wheel(event);
}, false);

在这个画布"元素之外,滚动需要发生.在里面,它必须只触发 .wheel() 方法.我做错了什么?

Outside of this "canvas" element, the scroll needs to happen. Inside, it must only trigger the .wheel() method. What am I doing wrong?

推荐答案

您可以通过在处理程序 (OG) 的末尾返回 false 来实现.

You can do so by returning false at the end of your handler (OG).

this.canvas.addEventListener('wheel',function(event){
    mouseController.wheel(event);
    return false; 
}, false);

或者使用 event.preventDefault()

this.canvas.addEventListener('wheel',function(event){
    mouseController.wheel(event);
    event.preventDefault();
}, false);

更新为使用 wheel 事件,因为 mousewheel 已在评论中指出,现代浏览器已弃用.

Updated to use the wheel event as mousewheel deprecated for modern browser as pointed out in comments.

问题是关于防止滚动无法提供正确的事件,因此请检查您的浏览器支持要求,以根据您的需要选择正确的事件.

The question was about preventing scrolling not providing the right event so please check your browser support requirements to select the right event for your needs.

使用更现代的方法选项进行了第二次更新.

Updated a second time with a more modern approach option.

这篇关于Javascript:捕获鼠标滚轮事件而不滚动页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆