2017-09-03 63 views
-4

我試圖在我的網站(www.trianglesquad.com)上做一個「點擊滾動」菜單。我嘗試了 w3schools.com「https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_animate_smoothscroll」的代碼。我面臨一個問題。它不滾動到完美點。例如,如果我點擊「投資組合」,它會滾動到投資組合部分的中間。它在3-4次點擊後滾動至完美點。 任何幫助將不勝感激:)jQuery平滑滾動到元素 - 不能正常工作

謝謝。

+1

請發佈您到目前爲止嘗試過的相關HTML和JS代碼。 –

+1

歡迎來到stackoverflow - 很高興有你。請閱讀[我如何提出一個好問題?](https://stackoverflow.com/help/how-to-ask)和[如何創建一個最小,完整和可驗證的示例](https:// stackoverflow。 com/help/mcve)幫助保持最高級別的計算器內容,並增加獲得正確答案的機會。 – Axel

回答

0

不知道爲什麼所有的反對票,因爲我們都是在某個階段的初學者...也許對於未來的職位,嘗試創建一個JS小提琴與示例,並更具體。

您可以更改滾動通過增加或減去偏移補償按下面的例子:

$(document).ready(function(){ 
    // Add smooth scrolling to all links 
    $("a").on('click', function(event) { 

    // Make sure this.hash has a value before overriding default behavior 
    if (this.hash !== "") { 
     // Prevent default anchor click behavior 
     event.preventDefault(); 

     // Store hash 
     var hash = this.hash; 

     // Using jQuery's animate() method to add smooth page scroll 
     // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area 
     $('html, body').animate({ 
     scrollTop: $(hash).offset().top -200 
     }, 800, function(){ 

     // Add hash (#) to URL when done scrolling (default click behavior) 
     window.location.hash = hash; 
     }); 
    } // End if 
    }); 
}); 

關鍵帶走這裏是這一行:

scrollTop: $(hash).offset().top -200 

可以增加或減少您選擇的任意數量的像素。

編輯:

其實試試這個代碼,而不是:

$(document).ready(function() { 

$("#xp-navigation").find("a[href*=#]:not([href=#])").click(function() { 
     var offset = 0; 
     var speed = 1000; 
     var target = $(this.hash); 

     $("html,body").animate({ 
      scrollTop: target.offset().top - offset 
     }, speed); 
    }); 

}); 

這是一個有點清潔,還可以調整偏移。