Javascript 鼠标滚轮自动滚动到下一个锚点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25839487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:56:27  来源:igfitidea点击:

Auto-Scroll to next anchor at Mouse-wheel

javascriptjqueryhtmlanchoranchor-scroll

提问by Bondsmith

I have 5 anchors on my html page. Is there any way that the page scrolls automatically to the next anchor (#) by a single Mouse-wheel scroll? Is there a way that it happens regardless of the anchor's name? just to the next anchor.

我的 html 页面上有 5 个锚点。有什么办法可以通过单个鼠标滚轮滚动页面自动滚动到下一个锚点 (#)?不管锚的名字如何,有没有办法让它发生?只是到下一个锚点。

回答by Rick Hitchcock

This works in Chrome, IE, Firefox, Opera, and Safari:

这适用于 Chrome、IE、Firefox、Opera 和 Safari:

(function() {
  var delay = false;

  $(document).on('mousewheel DOMMouseScroll', function(event) {
    event.preventDefault();
    if(delay) return;

    delay = true;
    setTimeout(function(){delay = false},200)

    var wd = event.originalEvent.wheelDelta || -event.originalEvent.detail;

    var a= document.getElementsByTagName('a');
    if(wd < 0) {
      for(var i = 0 ; i < a.length ; i++) {
        var t = a[i].getClientRects()[0].top;
        if(t >= 40) break;
      }
    }
    else {
      for(var i = a.length-1 ; i >= 0 ; i--) {
        var t = a[i].getClientRects()[0].top;
        if(t < -20) break;
      }
    }
    if(i >= 0 && i < a.length) {
      $('html,body').animate({
        scrollTop: a[i].offsetTop
      });
    }
  });
})();

Fiddle at http://jsfiddle.net/t6LLybx8/728/

小提琴在http://jsfiddle.net/t6LLybx8/728/

How it works

这个怎么运作

To monitor the mouse wheel in most browsers, use $(document).on('mousewheel'). Firefox is the oddball, and it requires $(document).on('DOMMouseScroll').

要在大多数浏览器中监视鼠标滚轮,请使用$(document).on('mousewheel'). Firefox 是个怪人,它需要$(document).on('DOMMouseScroll').

To get the direction of the mouse wheel (up or down), use event.originalEvent.wheelDelta. Again, Firefox is the oddball, and you have to use -event.originalEvent.detail.

要获得鼠标滚轮的方向(向上或向下),请使用event.originalEvent.wheelDelta. 同样,Firefox 是个怪人,你必须使用-event.originalEvent.detail.

If the direction is a negative number, you're scrolling downthe page. In that case, loop through each tag beginning with the first, until its first getClientRects()top is >= 40. (I used 40, in case the browser adds a default margin at the top of the viewport.)

如果方向为负数,则您正在向下滚动页面。在这种情况下,循环遍历从第一个开始的每个标签,直到它的第一个getClientRects()顶部 >= 40。(我使用了 40,以防浏览器在视口顶部添加默认边距。)

If the direction is a positive number, you're scrolling upthe page. In that case, loop through each tag beginning with the last, until its first getClientRects()top is < -20. (I used -20 to ensure we move up the page.)

如果方向是正数,则您正在向上滚动页面。在这种情况下,循环遍历从最后一个开始的每个标签,直到它的第一个getClientRects()顶部 < -20。(我使用 -20 来确保我们向上移动页面。)

The delayvariable prevents the mouse wheel from scrolling too quickly. The entire function is wrapped in a closure, so delayremains a private variable.

delay变量可防止鼠标滚轮滚动过快。整个函数被包裹在一个闭包中,所以delay仍然是一个私有变量。

回答by suish

let's say you have array of IDs.then you can do something like...

假设您有一组 ID。那么您可以执行以下操作...

  var ancherList = ["id1","id2","id3"];
  var currentPosition = null;

  var mousewheelevent = 'onwheel' in document ? 'wheel' : 'onmousewheel' in document ? 'mousewheel' : 'DOMMouseScroll';
  $(document).on(mousewheelevent,function(e){
      var scrollToAncher function (id,speed){
          spd = speed ? "slow" //deafult value for the animation speed
          var ancherTag = $("a[name='"+ id +"']");
          $('html,body').animate({scrollTop: ancherTag.offset().top},spd);
      }
      e.preventDefault();
      var delta = e.originalEvent.deltaY ? -(e.originalEvent.deltaY) : e.originalEvent.wheelDelta ? e.originalEvent.wheelDelta : -(e.originalEvent.detail);
      if (delta > 0){
          console.log("up")
          //check your current position and target id
          switch(currentPosition){
            case null :
            case ancherList[0] :
              scrollToAncher(ancherList[1]);
              currentPosition = ancherList[1];
              break;
            case ancherList[1] :
              currentPosition = ancherList[2];
              scrollToAncher(ancherList[2]);
              break;
            case ancherList[2] :
              currentPosition = ancherList[0];
              scrollToAncher(ancherList[0]);
              break;              
          }
      } else {
          console.log("down")
          //do the same for mouse wheel down
      }
  });

code ain't tested.sorry if there was syntax error

代码没有经过测试。如果有语法错误,抱歉