我正在使用JavaScript在我的网站上实现平滑滚动,我遇到了CSS scroll-margin-top导致结尾跳转的问题.我使用以下css来实现滚动页边距:

class or div {
  scroll-margin-top: 6rem;/*any size*/
}

我也有一个流畅的滚动脚本功能.问题是,当滚动到这些部分时,当到达滚动的末尾时,会出现明显的 skip .

以下是该脚本的代码:

    var ssSmoothScroll = function () {
      $('a[href^="#"], area[href^="#"]').on('click', function (e) {
        var target = $($(this).attr('href'));
        if (target.length) {
          e.preventDefault();
          $('html, body').stop().animate({
            scrollTop: target.offset().top
          }, cfg.scrollDuration, 'swing', function () {
            window.location.hash = target.attr('id');
          });
        }
      });
    };  

如何才能在不跳转的情况下解决这个问题并保持流畅的滚动?

The JsFiddle demo

推荐答案

目标元素的值scroll-margin-top,并从滚动目标中减go 该值.

$(document).ready(function () {
  $('a[href^="#"], area[href^="#"]').on('click', function (e) {
    var target = $($(this).attr('href'));
    if (target.length) {
      e.preventDefault();
      var scrollMargin = target.css('scroll-margin-top'); // Get scroll-margin-top value
      var offset = scrollMargin ? parseInt(scrollMargin) : 0; // Parse the value
      $('html, body').stop().animate({
        scrollTop: target.offset().top - offset // Consider scroll-margin-top
      }, 1000, 'swing', function () {
        window.location.hash = target.attr('id');
      });
    }
  });
});
 body {
      margin: 0;
      padding: 0;
    }
    
    #first,
    #second,
    #third,
    #fourth,
    #fifth {
      scroll-margin-top: 6rem;
    }

    /* Additional styles for demonstration purposes */
    section {
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 2rem;
    }
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
 <nav>
    <ul>
      <li><a href="#first">first</a></li>
      <li><a href="#second">second</a></li>
      <li><a href="#third">third</a></li>
      <li><a href="#fourth">fourth</a></li>
      <li><a href="#fifth">fifth</a></li>
    </ul>
  </nav>

  <section id="first">first</section>
  <section id="second">second</section>
  <section id="third">third</section>
  <section id="fourth">fourth</section>
  <section id="fifth">fifth</section>

Javascript相关问答推荐

没有输出到带有chrome.Devtools扩展的控制台

Spring boot JSON解析错误:意外字符错误

如何使用JavaScript将文本插入空div

将字符串UTC Date转换为ngx—counting leftTime配置值的数字

切换时排序对象数组,切换不起作用

在286之后恢复轮询

未定义引用错误:未定义&Quot;而不是&Quot;ReferenceError:在初始化&Quot;之前无法访问';a';

ChartJs未呈现

为什么123[';toString';].long返回1?

使用领域Web SDK的Vite+Vue应用程序中的Web程序集(WASM)错误

在Reaction中的handleSubmit按钮内,useSelector值仍然为空

创建以键值对为有效负载的Redux Reducer时,基于键的类型检测

一个实体一刀VS每个实体多刀S

如何利用CSS中的隐藏元素实现平滑扩展和防止网格行间隙

P5.js中矩形内的圆弧

如何创建一个for循环,用于计算仪器刻度长度并将其放入一个HTML表中?

如何使用useparams从react路由中提取id

通过ng-绑定-html使用插入的HTML中的函数

检测带有委托的元素内部的点击,以及元素何时按其类名被选中

如何在单击Search按钮时更新Reaction组件?