Javascript将功能绑定到鼠标滚轮

时间:2012-10-29 14:33:35

标签: javascript html anchor internal-link

我有一个单页网站,它使用内部锚点来呈现多个页面的错觉。我编写了一个javascript函数,用于从用户上下读取鼠标滚轮,并根据该函数将用户发送到当前页面上方/下方的锚点。该功能正如所描述的那样正常工作,但鼠标滚轮非常敏感,最轻微的移动会触发多个鼠标滚轮事件,并向用户发送多页上下文件,而不只是一页。

我需要一种方法来限制我的鼠标滚轮功能执行的次数,这样用户只能在鼠标滚轮的任一方向上移动一页,无论使用鼠标滚轮的速度是多快。我的javascript在下面。

<script>
$(document).ready(function(){
$("#main").bind('mousewheel', function(event) {
if (event.originalEvent.wheelDelta >= 0) {
var currentPage = $(".active").attr('href');
switch(currentPage){
case "#publications":
    window.location = $("#menu-item-290 a").attr('href');
    break;
case "#branding":
    window.location = $("#menu-item-106 a").attr('href');
    break;
case "#website-development":
    window.location = $("#menu-item-110 a").attr('href');
    break;
case "#about-us":
    window.location = $("#menu-item-109 a").attr('href');
    break;
case "#contact":
    window.location = $("#menu-item-108 a").attr('href');
    break;
}

}
else {
var currentPage = $(".active").attr('href');
switch(currentPage){
case "#home":
    window.location = $("#menu-item-106 a").attr('href');
    break;
case "#publications":
    window.location = $("#menu-item-110 a").attr('href');
    break;
case "#branding":
    window.location = $("#menu-item-109 a").attr('href');
    break;
case "#website-development":
    window.location = $("#menu-item-108 a").attr('href');
    break;
case "#about-us":
    window.location = $("#menu-item-107 a").attr('href');
    break;
}

}
 });
});
</script>

2 个答案:

答案 0 :(得分:0)

不是直接在鼠标滚轮上转到页面的一部分,而是设置一个非常短的setTimeout(大约50毫秒左右)去你想去的地方,如下:

case "#home":
    var timeout = null;
    timeout = setTimeout('window.location = $("#menu-item-106 a").attr("href")', 50);
    break;

这样,如果连续快速连续发生20个鼠标滚轮事件,您只需触发想要执行一次的操作。

答案 1 :(得分:0)

您已经在查询wheelDelta,为什么不使用它? According to MSDN它“表示车轮旋转的距离,以120的倍数表示”。因此,只需将您的if语句更改为>= 360,并在if添加else作为负数。