【问题标题】:Scrolling starts at the wrong offset on chrome but works fine on firefox滚动从 chrome 上的错误偏移开始,但在 Firefox 上工作正常
【发布时间】:2017-09-18 12:14:53
【问题描述】:

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

$(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);
});

当我尝试导航到网站中的“关于部分”时,这是我在控制台中看到的内容。

Website demo

【问题讨论】:

    标签: javascript jquery html scroll smooth-scrolling


    【解决方案1】:

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

    $('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);
    });
    

    【讨论】:

      猜你喜欢
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      • 2016-03-02
      • 1970-01-01
      • 1970-01-01
      • 2012-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多