主动锚定导航

时间:2013-05-31 17:35:51

标签: jquery css smooth-scrolling

我的单页网站目前使用箭头键平滑滚动到锚点。问题是,当您滚动到每个部分时,悬停的链接不会跟随每个部分。它只跟随你的箭头键命令。我怎么能改变这个?这是当前的网站(http://www.jonasandnicole.com

CSS

nav.desktop a {
    padding-top:10px;
    padding-bottom:10px;
    text-align:right;
    padding-right:20px;
    color:#CCC;
    -moz-transition: background 0.7s ease;
    -ms-transition: background 0.7s ease;
    -o-transition: background 0.7s ease;
    -webkit-transition: background 0.7s ease;
}
nav.desktop a:hover {
    background-color:rgba(0, 0, 0, 0.5);
    color:#fff;
}
.selected {
    background-color:rgba(0, 0, 0, 0.3);
}

的jQuery

<script src="js/jquery.easing.1.3.js"></script>
<script>
$(document).ready(function() {
    $(".desktop a").click(function() {
        $(".desktop a").removeClass("selected");
        $(this).addClass("selected"); 
    });
});
$(function() {
    var lengthDiv = $('.desktop').find('li').length;
    var current = 0;
    $('a').bind('click',function(event){
        var $anchor = $(this);
        current = $anchor.parent().index();

        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href#')).offset().top
        }, 1500,'easeInOutExpo');
        /*
        if you don't want to use the easing effects:
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1000);
        */
        event.preventDefault();
    });
    $(document).keydown(function(e){if($(':focus').length <= 0)e.preventDefault()})
    $(document).keyup(function(e){
        var key = e.keyCode;
        if(key == 38 && current > 0){
            $('.desktop').children('li').eq(current - 1).children('a').trigger('click')
        }else if(key == 40 && current < lengthDiv){
            $('.desktop').children('li').eq(current + 1).children('a').trigger('click')
        }
    })
});

</script>

1 个答案:

答案 0 :(得分:3)

您要做的是在窗口到达某些滚动点时设置事件。您可以通过$ .scroll()或使用waypoints等库来完成此操作。作为使用航点的一个例子:

$('#target').waypoint(function(dir)) {
  $('nav <a> elements').removeClass('selected');
  switch(dir) {
    case 'down':
      $('corresponding <a> selector').addClass('selected');
      break;
    case 'up':
      $('previous <a> selector').addClass('selected');
  }
}

这需要针对每个目标元素进行。