2017-09-03 137 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); 
    }); 

}); 

这是一个有点清洁,还可以调整偏移。