Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

Javascript: Capture mouse wheel event and do not scroll the page?

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

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);

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

Or using event.preventDefault()

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...