JAVASCRIPT:鼠标滚轮转动

时间:2013-11-06 13:14:33

标签: javascript jquery mousewheel

我有一个没有滚动的页面。

如何在鼠标滚轮转动时设置警报(例如)?

例如,当鼠标滚轮打开元素时:

$(document).ready(function(){
  $('#div').mouseWheel(function(){
    alert('test');
  });
});

2 个答案:

答案 0 :(得分:2)

您可以检测滚动,但无法通过鼠标滚轮,滚动条,指垫,触摸屏或其他方法检测滚动。

您在浏览器中获得的只是一个滚动事件。

我猜这不是你想听到的。遗憾。

答案 1 :(得分:2)

好的,如果你需要鼠标滚轮,你应该考虑jquery-mousewheel plugin。你可以在那里绑定鼠标轮'事件

此事件还附带deltaX和deltaY信息,您可以从中推断出鼠标滚轮是向上滚动(deltaY> 0)还是向下滚动(deltaY <0)。

使用鼠标滚轮上/下检测在action 中查看

HTML:

<div id="mydiv" style="background: green; width: 400px; height: 400px;">
    a div
</div>

JAVASCRIPT:

$('#mydiv').hover(function() {
   $(this).data('hover',1); // mouse is over the div
}, function(){
   $(this).data('hover',0); // mouse is no longer over the div
});

$(document).mousewheel(function(event, delta, deltaX, deltaY) {
    if($('#mydiv').data('hover') == 1 && $(document).attr('alert-on') != 1) {
        $(document).attr('alert-on', 1) 
        if(deltaY > 0) {
            alert('wheel scrolls up');
        } else {
            alert('wheel scrolls down');
        }
        $(document).attr('alert-on', 0) 
    }
});

它的作用是当鼠标结束时在你的div上设置一个标志,一旦捕获到鼠标轮事件,它会用鼠标检查你是否超过<div>,当它显示警告框时。

它还在文档上设置了一个显示警告框的标志,因为每次转动滚轮时会发出鼠标滚轮事件,这会导致许多警报框堆叠在一起。