Javascript空格键滚动到页面上的下一个锚点

时间:2015-08-11 07:55:47

标签: javascript jquery html

我有一个包含多个锚点的单页网站。我正在引用此fiddle example,以便在使用鼠标滚轮时将页面推进到下一个锚点。有没有办法让我修改它以便也考虑空格键滚动?

(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;
      }
    }
    $('html,body').animate({
      scrollTop: a[i].offsetTop
    });
  });
})();

1 个答案:

答案 0 :(得分:0)

http://jsfiddle.net/kamikazefish/t6LLybx8/201/

(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 links = document.getElementsByTagName('a');
    var link;
    if(wd < 0) {
        link = findNext(links);
    }
    else {
        link = findPrevious(links);
    }

    animate(link);
  });

    $('body').keydown(function(e){
       if(e.keyCode == 8){
           e.preventDefault();
           // user has pressed backspace
           var links = document.getElementsByTagName('a');
           link = findPrevious(links);
           animate(link);
       }
       if(e.keyCode == 32){
           e.preventDefault();
           // user has pressed space
           var links = document.getElementsByTagName('a');
           link = findNext(links);
           animate(link);
       }
    });

  function findNext(links) {
       for(var i = 0 ; i < links.length ; i++) {
        var t = links[i].getClientRects()[0].top;
        if(t >= 40) return links[i];
      }
  }

  function findPrevious(links) {
      for(var i = links.length-1 ; i >= 0 ; i--) {
        var t = links[i].getClientRects()[0].top;
        if(t < -20) return links[i];
      }
  }

  function animate(link) {
    if( link ) {
      $('html,body').animate({
        scrollTop: link.offsetTop
      });
    }
  }
})();