如何使用jQuery在页面底部单击按钮滚动到某个元素/ div?

时间:2020-10-12 06:22:17

标签: javascript jquery

我已经尝试过对此进行各种更改,但它仍然对我不起作用。我正在尝试添加动画,以便在单击按钮时将其向下滚动到页面上的特定元素。

这是我的代码:

   <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> 

2 个答案:

答案 0 :(得分:0)

使用没有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>

答案 1 :(得分:0)

尝试一下:

<script> 
  $(document).ready(function() { 
    $("#nav-projects").click(function() { 
        $("html, body").animate({ 
            scrollTop: $( 
              #id).height() 
        }, 2000); 
    }); 
   });
 </script>

用您要滚动到的元素的ID替换ID并相应地调整高度。

相关问题