2016-11-23 122 views
0

我有一個導航欄,它固定到屏幕頂部後,它向上滾動160px。如果導航欄已經固定在屏幕的頂部,我也可以使用平滑的滾動條進行定位鏈接,但是如果導航欄在滾動160px之前處於其未定義狀態,則錨點滾動條不會進入說明我添加的40px緩衝區。滾動以固定導航欄錨定,導航滾動後修復導航

我希望平滑滾動滾動到正確-40px的錨點,不管導航欄是否固定。是

的兩批我使用的代碼如下:

1)平滑滾動

jQuery(document).ready(function($) { 
    $('a[href*="#"]:not([href="#"])').click(function() { 
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { 
     var target = $(this.hash); 
     target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
     if (target.length) { 
     $('html, body').animate({ 
      scrollTop: target.offset().top - 40 
     }, 750); 
     return false; 
     } 
    } 
    }); 
}); 

2)固定導航欄

jQuery(document).ready(function($){ 
    $(function() { 
     $(window).resize(function() { 
     // responsive nav primary fixed 
     if (window.innerWidth > 960) { 
      $(window).bind('scroll', function(){ if ($(window).scrollTop() > 160) {$('.nav-primary').addClass('nav-primary-fixed');} else {$('.nav-primary').removeClass('nav-primary-fixed');}}); 
     } else {} 
     // end responsive nav primary fixed 
    }) .resize(); // trigger resize event 

    }); 
}); 

任何想法?

在此先感謝。

+1

檢查導航欄是否具有「nav-primary-fixed」類,然後相應地修改40值......? – CBroe

+0

我不確定你是否誤解了這個問題。如果網站已經滾動超過160像素,並且導航欄已分配了「nav-primary-fixed」,則錨點滾動完美。如果站點沒有從頂部滾動並且導航欄尚未修復,它不會正確對齊錨點。因此,例如在頁面加載時,如果我點擊並錨定鏈接,它將滾動到錨點,但錨點的頂部將隱藏在導航欄後面40px。 如果你的解決方案是前進的正確方法,我不知道如何去編碼到我當前的代碼。 – SharpenedPixels

+1

只有在導航欄被固定的情況下,您才需要這些40px的偏移量。因此,檢查它是否(.hasClass) - 並根據這一點,減去那些40px,或不。 – CBroe

回答

1

好吧,在CBroe的一些幫助下,我對.hasClass做了一些研究,並發現了一些文章,幫助我找到了解決問題的方法,下面的jQuery代碼是修改過的,現在正在工作,根據需要,代碼:

jQuery(document).ready(function($) { 
    $('a[href*="#"]:not([href="#"])').click(function() { 
    if (location.pathname.replace(/^\//,'') === this.pathname.replace(/^\//,'') && location.hostname === this.hostname) { 
     var target = $(this.hash); 
     target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
     if ($(".nav-primary").hasClass("nav-primary-fixed")) { 
     if (target.length) { 
      $('html, body').animate({ 
      scrollTop: target.offset().top - 40 
      }, 750); 
      return false; 
     } 
     } else { 
     if (target.length) { 
      $('html, body').animate({ 
      scrollTop: target.offset().top - 80 
      }, 750); 
      return false; 
     } 
     } 
    } 
    }); 
}); 
+1

太好了,但你仍然可以縮短一點。看看if-和else-分支,它們的代碼與實際使用的值相同。所以爲什麼不把這個值存儲到一個變量中,然後將代碼放入if和else中,使用變量代替40/80 ... – CBroe

+0

我已經添加了另一個elseif語句來應用另一個對於屏幕寬度小於960像素的值,因爲移動設備和平板電腦無法正確對齊定位點,而我已經修復了所有問題。 我確實嘗試過類似的東西,但它不起作用,但之後我沒有嘗試使用工作代碼中使用的確切if,elseif,else語句,所以如果我再次修改它,我可以縮短爲你建議。再次感謝。 – SharpenedPixels