簡體   English   中英

如何使“滾動到頂部”JS function go 在 JQuery 中變慢

[英]How to make "scroll to top" JS function go slower in JQuery

如何僅使用 JQuery 從 W3 學校編輯此代碼以使其滾動速度變慢? 它目前只是跳到頂部。 有沒有辦法減慢它的速度,以便用戶可以看到他們實際上是回到頁面頂部? 理想情況下,如果可能的話,整個事情應該在 JQuery 中。

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_scroll_to_top

 //Get the button var mybutton = document.getElementById("myBtn"); // 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) { mybutton.style.display = "block"; } else { mybutton.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; } #myBtn { display: none; position: fixed; bottom: 20px; right: 30px; z-index: 99; font-size: 18px; border: none; outline: none; background-color: red; color: white; cursor: pointer; padding: 15px; border-radius: 4px; } #myBtn:hover { background-color: #555; }
 <body> <button onclick="topFunction()" id="myBtn" title="Go to top">Top</button> <div style="background-color:black;color:white;padding:30px">Scroll Down</div> <div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible <strong>when the user starts to scroll the page</strong>.</div>

您正在尋找平滑滾動,這是一個 css 屬性; 和/或您正在尋找 jQuery.animate() 方法。 查看:

https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2

他們正在使用 this.hash 找到平滑滾動的目的地。 您可以省略它,並將其替換為“0”以滾動到頂部。 如果您對 this.hash 不熟悉,請查看:

$(this.hash) 是如何工作的?

添加樣式:

html {
        scroll-behavior: smooth;
    }

或將 jQuery 添加到您的 html 頭中:

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

並將您的 topFunction 替換為:

function topFunction() {
 
    $('html, body').animate({
        scrollTop: 0
      }, 500);
}

“500”是滾動 animation 的持續時間,以毫秒為單位。

您可以嘗試使用具有smooth行為https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo#examplesscrollTo

Though it doesn't work on Safari (I see it works only from Safari 14 and on now), for safari you need to add a polyfill https://github.com/iamdustan/smoothscroll

只需像這樣擴展您的 scrollTop 調用:

window.scrollTo({top: 0, behavior: 'smooth'});

暫無
暫無

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

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