在平滑滚动上添加保证金

时间:2017-07-26 01:36:46

标签: jquery offset smooth-scrolling

我正在为我的单页自由网站添加smoothscrolling。 每当它滚动到页面时,它会显示距离固定顶部导航部分bc顶部的60px,当它向下滚动时滚动显示为

this

如果我想将它向下推60px并向下滚动看起来像这样。

enter image description here

我从w3 bc中提取了滚动码,他们的解决方案似乎最简单。刚开始使用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>

2 个答案:

答案 0 :(得分:1)

我实际上是要通过在$(hash).offset()之后添加--60来解决这个问题.top

如果其他人遇到此问题,则更改部分:

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

答案 1 :(得分: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;
            } );
        }
    } );
} );