javascript - 平滑滚动解决方法

标签 javascript jquery html css smooth-scrolling

我正在使用固定在最大宽度 1000 像素的导航栏。高度为 60px。

我的问题是页面跳转不会到达它应该到达的地方。

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

最佳答案

做到了!这将向后移动 60px,屏幕最大宽度为 1000px

$(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 (matchMedia('only screen and (max-width: 1000px)').matches) {
        $('html,body').animate({
          scrollTop: target.offset().top -60
        }, 1000);

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

关于javascript - 平滑滚动解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33877751/

相关文章:

html - 快速响应的交互式图表/图形 : SVG, Canvas,其他?

html - 封装CSS

javascript - 从 wav 文件中读取样本

javascript - setinterval 无法更改图像 src

javascript - 如何在循环执行时逐渐将内容附加到 div?

html - 是否垂直对齐 :center-right; works?

javascript - Firefox 插件中的 window.location.replace 删除了整个 chrome!

javascript - 单击按钮时选择框出现/消失

javascript - 您如何在两个浏览器选项卡/窗口之间进行通信?

javascript - jQuery 对话框/javascript bool 值不起作用