簡體   English   中英

如何使用 jQuery 單擊按鈕滾動到頁面底部的某個元素/div?

[英]How to scroll on click of a button to a certain element/div on the bottom of the page with 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> 

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

嘗試這個:

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

將 id 替換為您希望滾動到的元素的 id,並相應地調整高度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM