0

我有一个导航栏,它在向上滚动 160 像素后固定在屏幕顶部。我还对锚链接使用平滑滚动,如果导航栏已经固定到屏幕顶部,效果很好,但是如果导航栏在向上滚动 160px 之前处于未固定状态,则锚滚动不会考虑记下我添加的 40px 缓冲区。

无论导航栏是否固定,我都希望平滑滚动准确地滚动到锚点 -40px。

我正在使用的两批代码如下:

1) 平滑滚动

jQuery(document).ready(function($) {
  $('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top - 40
        }, 750);
        return false;
      }
    }
  });
});

2) 固定导航栏

jQuery(document).ready(function($){
    $(function() {
        $(window).resize(function() {
        // responsive nav primary fixed
        if (window.innerWidth > 960) {
            $(window).bind('scroll', function (){ if ($(window).scrollTop() > 160) {$('.nav-primary').addClass('nav-primary-fixed');} else {$('.nav-primary').removeClass('nav-primary-fixed');}});
        } else {}
        // end responsive nav primary fixed
    }) .resize(); // trigger resize event

    });
});

有任何想法吗?

提前致谢。

4

1 回答 1

1

好的,在 CBroe 对问题的评论中提供了一点帮助,我做了一些研究.hasClass,发现了一些帮助我找到解决方法的文章,下面的 jQuery 代码是经过修改的,现在可以根据需要运行代码:

jQuery(document).ready(function($) {
  $('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') === this.pathname.replace(/^\//,'') && location.hostname === this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if ($(".nav-primary").hasClass("nav-primary-fixed")) {
        if (target.length) {
          $('html, body').animate({
            scrollTop: target.offset().top - 40
          }, 750);
          return false;
        }
      } else {
        if (target.length) {
          $('html, body').animate({
            scrollTop: target.offset().top - 80
          }, 750);
          return false;
        }
      }
    }
  });
});
于 2016-11-23T17:02:50.307 回答