jQuery 平滑滚动定位:设置距离顶部偏移停止位置


发布日期 : 2024-06-27 02:15:46 UTC

访问量: 9 次浏览

如何用jQuery设置平滑滚动在距离顶部的特定位置停止

jQuery 中的 scrollTop() 方法是用来滚动到页面的一个特定部分。用现有的内置动画对该方法进行动画处理,可以使滚动更加平滑。而且,从该方法中减去指定的值将使滚动从顶部停止。

方法:
首先使用哈希属性提取锚定链接的哈希部分,并使用 offset() 方法找出它在页面上的位置。然后对这个哈希值调用 scrollTop() 方法,以滚动到该位置。这个方法通过在 animate() 方法中包围它,并指定要使用的动画的持续时间(以毫秒为单位)来实现动画。一个较大的值会比一个较小的值使动画完成得更慢。这将使页面上的所有锚点链接在被点击时平滑地产生动画。然后我们将减去指定的值,使平滑滚动从顶部停止。

示例:

<!DOCTYPE html>
<html>
  
<head>
     <title>
         How to set smooth scrolling to stop at
         a specific position from the top using
         jQuery?
     </title>
  
     <!-- JQuery Script -->
     <script src=
         "https://code.jquery.com/jquery-3.4.1.min.js">
     </script>
  
     <!-- Style to make scrollbar appear -->
     <style>
         .scroll {
             height: 1000px;
             background-color: teal;
             color: white;
         }
     </style>
</head>
  
<body>
     <h1 style="color: green">
         GeeksforGeeks
     </h1>
  
     <b>
         How to set smooth scrolling to stop at
         a specific position from the top using
         jQuery?
     </b>
  
     <p id="dest">
         Click on the button below to
         scroll to the top of the page.
     </p>
  
  
     <p class="scroll">
         GeeksforGeeks is a computer science
         portal. This is a large scrollable
         area.
     </p>
  
  
     <a href="#dest">
         Scroll to top
     </a>
  
     <!-- jQuery for smooth scrolling to a
         specific position from top -->
     <script>
  
         // Define selector for selecting
         // anchor links with the hash
         let anchorSelector = 'a[href^="#"]';
  
         $(anchorSelector).on('click', function (e) {
  
             // Prevent scrolling if the
             // hash value is blank
             e.preventDefault();
  
             // Get the destination to scroll to
             // using the hash property
             let destination = $(this.hash);
  
             // Get the position of the destination
             // using the coordinates returned by
             // offset() method and subtracting 50px
             // from it.
             let scrollPosition
                 = destination.offset().top - 50;
  
             // Specify animation duration
             let animationDuration = 500;
  
             // Animate the html/body with
             // the scrollTop() method
             $('html, body').animate({
                 scrollTop: scrollPosition
             }, animationDuration);
         });
     </script>
</body>
  
</html>

输出:

如何用jQuery设置平滑滚动在距离顶部的特定位置停止?