javascript - 平滑滚动会奇怪地跳跃

标签 javascript jquery smooth-scrolling

$(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
    }, 1000);
    if (target.length <= 1000) {
      $('html,body').animate({
        scrollTop: target.offset().top - 60
      }, 1000);
    };
    return false;
  }
}});});

我正在使用一个固定的导航栏,屏幕最大宽度 < 1000px。
导航栏的高度为 60px。因此,如果 max-with < 1000px,则动画会向后退 60px。

所有这些工作正常,但我的问题是,只有当视口(viewport)大于 1000px 时,页面才会奇怪地跳转。

最佳答案

我认为问题在于您没有阻止默认的点击事件。这意味着浏览器会跳转到您想要的#id(因为这是默认的浏览器行为),然后平滑滚动会从头开始触发动画,从而实现快速跳转。

要修复它,只需使用 preventDefault(); 阻止默认事件;

简单示例:

$('selector').click(function(e) {
    e.preventDefault();
    // your code
});

固定代码:

$(function() {
    $('a[href*=#]:not([href=#])').click(function(e) {e.preventDefault(); {
        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
                }, 1000);
                if (matchMedia('only screen and (max-width: 1000px)').matches) {
                    $('html,body').animate({
                        scrollTop: target.offset().top - 60
                    }, 1000);

                    window.location.hash = '#' + target[0].id;

                    return false;
                }
              }
            }
          }
    });
});

关于javascript - 平滑滚动会奇怪地跳跃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34858410/

相关文章:

JavaScript/Greasemonkey : Avoiding FireFox Security Warning when Submitting a Form from a Secure Page

javascript - 在 Javascript 中选择下拉列表而不使用 selectedindex

javascript - 如何通过jquery在所有链接中添加功能?

jquery - 使用 anchor 创建平滑滚动

javascript - 绝对定位内容的平滑滚动

javascript - 机车滚动 - 从水平切换到垂直并返回

javascript - 在 Mongoose 中返回关联数组而不是文档数组

javascript - 在 JS canvas 中绘制正弦波不执行任何操作

javascript - div 的响应高度 : shrink to a breakpoint then start growing again

javascript - 使用 Jquery 单击菜单链接时,在菜单选项卡链接上激活或添加事件类