2017-07-26 117 views
0

我将平滑滚动添加到我的单页自由网站。 每当滚动到页面它显示了从公元前修复顶部导航栏部分的顶部60像素的滚动看起来像这样,当它向下滚动在平滑滚动上添加边距

this

当我想它推60px下来,向下滚动看起来像这样。

enter image description here

我从公元前W3他们的解决方案似乎是最简单的拉滚动码。刚开始使用jQuery更多,所以任何帮助将不胜感激。 下面的代码使用:

<script> 
    $(document).ready(function(){ 
    $(".navbar a, footer a[href='#myPage']").on('click', function(event) { 

    if (this.hash !== "") { 

     event.preventDefault(); 

     var hash = this.hash; 

     $('html, body').animate({ 
     scrollTop: $(hash).offset().top 
     }, 1100, function(){ 

     window.location.hash = hash; 
     }); 
     } // End if 
    }); 
    }) 
</script> 

回答

1

我其实有关的附加解决这个问题我自己 - 后顶部$(散)60 .offset()顶部

更改部分,如果任何人有过这样的问题:

('html, body').animate({ 
scrollTop: $(hash).offset().top - 60 
}, 1100, function(){ 
0

我会建议作出补偿基础上,.navbar高度,而不是硬编码的高度,所以如果内容的变化,或者你重用代码,你不必继续去改变它。您还可以改进脚本处理散列的方式,并允许以散列开头的任何URL具有平滑滚动:

$(function() { 
    $('a[href^="#"]').on('click', function(e) { 

     if (this.hash !== '') { 
      e.preventDefault(); 

      var hash = this.hash; 
      var nav = $('.navbar').outerHeight(); 

      $('html, body').animate({ 
       scrollTop: $(hash).offset().top - nav 
      }, 1100, function() { 
       window.location.hash = hash; 
      }); 
     } 
    }); 
});