首页 > 解决方案 > 如何使用 jQuery 单击按钮滚动到页面底部的某个元素/div?

问题描述

我已经尝试了不同的变体,但它仍然对我不起作用。我正在尝试添加一个动画,以便当我单击按钮时,它会向下滚动到页面上的某个元素。

这是我的代码:

   <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> 
</script> 

<!-- jQuery code to show the working of this method -->
<script> 
   $(document).ready(function() { 
        $("#nav-projects").click(function() { 
            $("html, body").animate({ 
                scrollTop: $( 
                  'html, body').get(0).scrollHeight 
            }, 2000); 
        }); 
    });
</script> 

标签: javascriptjquery

解决方案


没有 jQuery ( $('#yourelement').offset().top; ) 或 Javascript的 CSS 的另一种方法是:

html {
  scroll-behavior: smooth;
}
<a href="#A">Goto A</a>
<a href="#B">Goto B</a>
<a href="#C">Goto C</a>

<hr>

<div id="A" style="height:500px;">Section A</div>
<div id="B" style="height:500px;">Section B</div>
<div id="C" style="height:500px;">Section C</div>


推荐阅读