简体   繁体   English

区分鼠标滚轮滚动还是滚动条滚动?

[英]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. 我在Stackoverflow上搜索过,但似乎无法找到这个问题的满意答案。 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. 如果wheel事件发生在scroll事件之前,那么滚动就完成了滚轮,否则完成后使用其他东西然后滚轮。 There is a slight time difference between both events that are triggered thats why I use a threshold currTime - lastWheelTime > 30 . 触发的两个事件之间存在微小的时间差异,这就是我使用阈值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) (感谢@ t.niese的代码片段,我为我的演示做了一些修改)

 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 . 见jQuery的页面在这里

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. 读到这一点,看起来两个事件都会被解雇。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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