滚动页面以更改活动/当前菜单项

时间:2012-09-17 09:32:38

标签: javascript jquery menu scroll

我正在使用http://jsfiddle.net/mekwall/up4nu/来浏览一个寻呼机。单击菜单项时,如何停用当前标记?我想保持滚动。但是,当我在第一个项目并点击第四个项目时,我只想要第四个标记当前,没有标记“滑动”通过第二个和第三个项目。

我也尝试了onePageNav,但如果我的目标网页上没有内容(部分带有ID )的子页面,则会中断。

1 个答案:

答案 0 :(得分:2)

This应该可以工作:)我添加了一个noScrollAction变量。我在滚动动画开始之前设置它,并在它结束时禁用它。但是动画结束后窗口滚动仍然会触发(还没弄清楚原因)。所以我对它施加了额外的延迟。并为正确的锚点设置活动类。

// Cache selectors
var lastId,
    topMenu = $("#top-menu"),
    topMenuHeight = topMenu.outerHeight()+15,
    // All list items
    menuItems = topMenu.find("a"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function(){
      var item = $($(this).attr("href"));
      if (item.length) { return item; }
    }),
    noScrollAction = false;

// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e){
    var href = $(this).attr("href"),
        offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
    noScrollAction = true;
    $('html, body').stop().animate({ 
        scrollTop: offsetTop
    },{
        duration: 300,
        complete: function() {
            menuItems
                .parent().removeClass("active")
                .end().filter("[href=" + href +"]").parent().addClass("active");
            setTimeout(function(){ noScrollAction = false; }, 10);
        }
    });
    e.preventDefault();
});

// Bind to scroll
$(window).scroll(function(){
   if(!noScrollAction){
       // Get container scroll position
       var fromTop = $(this).scrollTop()+topMenuHeight;

       // Get id of current scroll item
       var cur = scrollItems.map(function(){
         if ($(this).offset().top < fromTop)
           return this;
       });
       // Get the id of the current element
       cur = cur[cur.length-1];
       var id = cur && cur.length ? cur[0].id : "";

       if (lastId !== id) {
           lastId = id;
           // Set/remove active class
           menuItems
             .parent().removeClass("active")
             .end().filter("[href=#"+id+"]").parent().addClass("active");
       }
   }    
});​
相关问题