简体   繁体   中英

Differentiate between mouse wheel scroll or scrollbar scroll?

I've searched on Stackoverflow but can't seem to find a satisfactory answer to this question. Basically I'd like to know if the scroll was done via mousewheel or the browser scrollbar.

Something like this might work for you but it is not the best solution.

If the a wheel event occurs right before the scroll event, then the scroll is done with the wheel otherwise it is done with using something else then the wheel. There is a slight time difference between both events that are triggered thats why I use a threshold currTime - lastWheelTime > 30 .

 $('.test').on('scroll wheel DOMMouseScroll mousewheel', function(e) { var lastWheelTime, currTime = (new Date()).getTime(); if( e.type === 'scroll' ) { lastWheelTime = $(this).data().lastWheelTime || 0; if( currTime - lastWheelTime > 30 ) { $('.info').text('no wheel'); } else { $('.info').text('with wheel'); } } else { $(this).data().lastWheelTime = (new Date()).getTime(); } }); 
 .test { width: 200px; height: 300px; border: 1px solid red; overflow: auto; } .inner { height: 600px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="info"></div> <div class="test"> <div class="inner"></div> </div> 

Here is my trick to detect scrolling by wheel or not
(Thanks @t.niese for the code snippet, I have made some modification for my demo)

 var withWheel = true; $('.test').on('scroll', function() { $(".info").text("with wheel: " + withWheel); }) $('.inner').on('mouseover', function() { withWheel = true; }).on('mouseleave', function(e) { e.stopPropagation(); withWheel = false; }); 
 .test { width: 200px; height: 300px; border: 1px solid red; overflow: auto; } .info { position: fixed; } .inner { height: 600px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="info"></div> <div class="test"> <div class="inner"></div> </div> 

I'd say both the wheel scroll and scrollbar scroll are the same. See the jquery page Here .

The scroll event is sent to an element when the user scrolls to a different place in the element. It applies to window objects

Reading this, it looks like the same event is going to be fired for both.

另一种可能的方法(我还没有尝试过)是检查滚动事件期间是否按下了鼠标按钮(一个必须单击滚动条,对吗?)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM