将导航固定到顶部,然后向主体添加边距

时间:2014-02-20 17:32:41

标签: javascript jquery html css

目前使用此:

    $(function(){ // document ready

      var stickyTop = $('.navigation-wrap').offset().top; // returns number 

      $(window).scroll(function(){ // scroll event  
        var windowTop = $(window).scrollTop(); // returns number
        if (stickyTop < windowTop) {
          $('.navigation-wrap').addClass('sticky');
        }
        else {
          $('.navigation-wrap').removeClass('sticky');
        }
      });

    });

然而,将导航完美地粘贴到屏幕顶部,但是...使用以下内容时:

$(document).ready(function () {
    $(document).on("scroll", onScroll);

    //smoothscroll
    $('a[href^="#"]').on('click', function (e) {
        e.preventDefault();
        $(document).off("scroll");

        $('a').each(function () {
            $(this).removeClass('navactive');
        });
        $(this).addClass('navactive');

        var target = this.hash,
            menu = target;
        $target = $(target);
        $('html, body').stop().animate({
            'scrollTop': $target.offset().top+2
        }, 500, 'swing', function () {
            window.location.hash = target;
            $(document).on("scroll", onScroll);
        });
    });
});

根据您滚动页面的距离突出显示当前按钮。问题是现在50px导航覆盖了内容的顶部。如果单击其中一个按钮,页面会向下滚动并覆盖标题。

是否有任何方法可以为代码添加50px的保证金,以便导航不会妨碍?我确实尝试使用偏移量,但无法使其工作。

1 个答案:

答案 0 :(得分:1)

是的,在这一行添加更多像素:

'scrollTop': $target.offset().top+2

例如:

'scrollTop': $target.offset().top+52

您可以查看a similar solution I proposed