2014-11-22 63 views
1

大家下午好,如何突出顯示滾動中的活動菜單項並單擊?

我想添加一個類active到當前的滾動菜單項並點擊。這是一個包含不同部分的單頁(長)頁面。當點擊一個項目時,活動狀態應該切換到當前狀態。

我想出了下面的代碼,但沒有現在怎麼我可以整合上面:

// Click event 
    $('#primary-navwrapper li a[href^="#"]').click(function(event) { 

     // Prevent from default action to intitiate 
     event.preventDefault(); 

     // The id of the section we want to go to 
     var anchorId = $(this).attr('href'); 

     // Our scroll target : the top position of the section that has the id referenced by our href 
     var target = $(anchorId).offset().top - offset; 
     console.log(target); 

     $('html, body').stop().animate({ scrollTop: target }, 500, function() { 
      window.location.hash = anchorId; 
     }); 

     return false; 
    }); 

希望有人有一個例子或一些好的建議如何做到這一點。

回答

0
<nav> 
    <a href="#" class="item">item</a> 
    <a href="#" class="item">item</a> 
    <a href="#" class="item">item</a> 
    <a href="#" class="item">item</a> 
</nav> 


var el = $(".item"), 
    yPos = 0; 


el.click(function(event){ 
    event.preventDefault(); 

    $(this).addClass("active").siblings().removeClass("active"); 
}); 
$(window).scroll(function(){ 

    yPos = $(this).scrollTop(); 

    //i'm almost sure that you will need to calculate offset of your section to know when to switch classes 

    if(yPos > 100){ 
     el.removeClass("active").eq(1).addClass("active"); 
    } 
    if(yPos > 200){ 
     el.removeClass("active").eq(2).addClass("active"); 
    } 
    //etc.... 
}); 
1

要在click添加active類是簡單的使用jQuery。你只需要這個代碼在單擊處理

//remove active from all anchor and add it to the clicked anchor 
     $('#primary-navwrapper li a[href^="#"]').removeClass("active") 
     $(this).addClass('active'); 

而且滾動部分,你需要監控的滾動條的位置,並與每一個頁面像這樣

//check the pages when scroll event occurs 
$(window).scroll(function(){ 
    // Get the current vertical position of the scroll bar 
    position = $(this).scrollTop(); 
    $('#primary-navwrapper li a[href^="#"]').each(function(){ 
      var anchorId = $(this).attr('href'); 
      var target = $(anchorId).offset().top - offset; 
      // check if the document has crossed the page 
     console.log(position,target); 
     if(position>=target){ 
      //remove active from all anchor and add it to the clicked anchor 
      $('#primary-navwrapper li a[href^="#"]').removeClass("active") 
      $(this).addClass('active'); 
     } 
    }) 

這裏是一個偏移量比較演示http://jsfiddle.net/k5afwfva/