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

时间:2014-12-16 19:43:48

标签: javascript jquery

我在Stackoverflow上搜索过,但似乎无法找到这个问题的满意答案。基本上我想知道滚动是通过鼠标滚轮还是浏览器滚动条完成的。

4 个答案:

答案 0 :(得分:6)

这样的事情可能适合你,但它不是最好的解决方案。

如果a wheel事件发生在scroll事件之前,那么滚动就完成了滚轮,否则就完成了使用其他东西然后使用滚轮。触发的两个事件之间存在微小的时间差异,这就是我使用阈值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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这是我检测滚轮滚动的技巧 (感谢@ 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>

答案 2 :(得分:0)

我说轮滚动和滚动条滚动都是一样的。请参阅jquery页面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

读到这个,看起来两个人都会被解雇。

答案 3 :(得分:0)

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

相关问题