最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

mouseevent - How to simulate mousewheel up or down with JavaScript? - Stack Overflow

programmeradmin6浏览0评论

I have a web app where with an immersive view. In this view I can zoom in or zoom out with the mouse wheel action.

What I would like to do is to create 2 buttons which call a JavaScript function and simulate the mouse wheel actions.

I tried with:

window.scrollTo(0,300);

But scrolling in my case doesn't zoom (it seems like only the mouse wheel action works).

How can I simulate the mouse wheel up or down?

I have a web app where with an immersive view. In this view I can zoom in or zoom out with the mouse wheel action.

What I would like to do is to create 2 buttons which call a JavaScript function and simulate the mouse wheel actions.

I tried with:

window.scrollTo(0,300);

But scrolling in my case doesn't zoom (it seems like only the mouse wheel action works).

How can I simulate the mouse wheel up or down?

Share Improve this question edited Aug 23, 2024 at 17:39 Danny Beckett 20.8k25 gold badges112 silver badges142 bronze badges asked Sep 28, 2017 at 16:38 SamboSambo 2811 gold badge2 silver badges12 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 16

So I solved my problem after some research.

Here is what I did:

I create a mouse event and pass it a wheel event:

var evt = document.createEvent('MouseEvents');
evt.initEvent('wheel', true, true); 

Then I can set deltaY depending on if you want a wheel up or a wheel down.

evt.deltaY = +120;
// evt.deltaY = -120

And you can pass this event to your element by doing:

element.dispatchEvent(evt);

I posted an Answer on firing a wheel event now, as initEvent is deprecated:

https://stackoverflow./a/72525302/16054918

You could adapt it to your needs or make the function more general.

You can use the $.animate() from JQuery. Here's an example:

$('html, body').animate({
  scrollTop: target.offset().top
}, 1000, function() {
   // Do something when animation is plete
});

Where target can be any DOM element you may want to scroll to or a number that determines the length to scroll.

You should check out http://api.jquery./animate for more information on this method.

发布评论

评论列表(0)

  1. 暂无评论