簡體   English   中英

如何使用javascript(無jQuery)動畫化滾動到頁面頂部的動畫?

[英]How to animate scrolling to top of page using javascript (no jQuery)?

我想在按下網頁按鈕以緩慢滾動回到頁面頂部時執行過渡。 我知道如何使用類更改來執行過渡,但是在這種情況下,我將如何做?

document.documentElement.scrollTop = 0;
document.body.scrollIntoView({behavior: 'smooth', block: 'start'});

也適用於任何其他DOM元素。 並且也用於水平滾動。

您可以使用以下代碼移動頁面頂部。

 // When the user scrolls down 20px from the top of the document, show the button window.onscroll = function() { scrollFunction() }; function scrollFunction() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { document.getElementById("myBtn").style.display = "block"; } else { document.getElementById("myBtn").style.display = "none"; } } // When the user clicks on the button, scroll to the top of the document function topFunction() { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; } 
 body { font-family: Arial, Helvetica, sans-serif; font-size: 20px; background: #ffffff; } #myBtn { display: none; position: fixed; bottom: 20px; right: 30px; z-index: 99; background-color: red; color: white; cursor: pointer; padding: 15px; border-radius: 4px; } #myBtn:hover { background-color: #555; } 
 <button onclick="topFunction()" id="myBtn" title="Go to top">Top</button> <div style="padding:30px">Scroll Down</div> <div style="padding:30px 30px 700px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div> 

暫無
暫無

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

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