滚动从chrome上的错误偏移开始,但在firefox上工作正常

时间:2017-09-18 12:14:53

标签: javascript jquery html scroll smooth-scrolling

我试图在我的网站导航中添加平滑滚动,但是我很难搞清楚为什么滚动首先在错误的偏移处开始然后正确移动。

$(window).on("scroll", function () {
        var scroll_start = window.scrollY;
        console.log(scroll_start);
        if (scroll_start > offset) {
           navToLight();
        } else {
           navToDark();
        }
});

这就是我处理导航锚点上的点击事件的方法:

 $('a.nav-link').on('click', function () {
     var target = $($(this).attr('href')).position().top;
     console.log("This is the target: "+target);
     $("html, body").animate({
         scrollTop: target
    }, 700);
});

这是我在控制台中尝试导航到" about部分"在网站上。

Figure 1

Website demo

1 个答案:

答案 0 :(得分:0)

浏览器也会为您滚动,您应该做的是停止传播并阻止对事件的默认:

$('a.nav-link').on('click', function (e) {
   e.preventDefault();
   e.stopPropagation();
   var target = $($(this).attr('href')).position().top;
   console.log("This is the target: "+target);
   $("html, body").animate({
     scrollTop: target
   }, 700);
});