簡體   English   中英

滾動/單擊時,活動錨鏈接未在固定導航上正確設置

[英]Active anchor links not getting set properly on fixed nav on scroll/click

我正在添加和刪除活動錨鏈接的類(顏色:紅色)。 問題是該類沒有根據部分進行一致地添加,我似乎沒有弄清楚這一點。

如何修改我的代碼,以使錨鏈接在其各自的部分始終位於頁面頂部時被“突出顯示”?

這是我的代碼:

    // for secondary nav
 var topRange      = 200,  // measure from the top of the viewport to X pixels down
     edgeMargin    = 20,   // margin above the top or margin from the end of the page
     contentTop = [];

 // Set up content an array of locations for secondary nav
 $('.overlay-box').find('a').each(function(){
    var href = $(this).attr('href');
    var name = href.substr(href.lastIndexOf('#')+1);
    contentTop.push( $('[name="' + name + '"]').offset().top );
 });

// adjust secondary nav on scroll
$(window).scroll(function(){
  var winTop = $(window).scrollTop(),
      bodyHt = $(document).height(),
      vpHt = $(window).height() + edgeMargin;  // viewport height + margin
  $.each( contentTop, function(i,loc){
   if ( ( loc > winTop - edgeMargin && ( loc < winTop + topRange || ( winTop + vpHt ) >= bodyHt ) ) ){
    $('.nav-bar li')
     .removeClass('anchor-selected')
     .eq(i).addClass('anchor-selected');
   }
  });
});

這是網站:

http://www.icontrol.com/what-we-do/platform-services/

我完全看不到您打算如何做。

我整理了一個jsfiddle來實現您的目標

希望它是您需要的:-)

http://jsfiddle.net/66ZbB/

$(document).ready(function() {
$('a').click(function() {
    $('a').removeClass('anchor-selected');
    var obj = $(this);
    $('html, body').animate({
        scrollTop: obj.offset().top
    }, 1000, function () {
        obj.addClass('anchor-selected');
    });
});
$(window).scroll(function() {
    $('a').removeClass('anchor-selected');
    //alert($(window).scrollTop() +":");
    $('a').each(function() {
        console.log($(this).offset.top);
        if (($(window).scrollTop() <= ($(this).offset().top)) && ($(window).scrollTop() > ($(this).offset().top - 20))) {
            $(this).addClass('anchor-selected');
        }
    });
});
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM