JavaScript 滾動到頁面頂部
Harshit Jindal
2023年10月12日

本教程講解如何使用 JavaScript 滾動到頁面頂部。
使用 window.scrollTo()
函式滾動到頁面頂部
視窗的 scrollTo()
方法用於滾動到頁面上的特定位置。它有兩個引數:我們要滾動到的點的 x
和 y
座標。我們可以將 x
和 y
傳遞為 0
來滾動到頁面頂部。
window.scrollTo(x - coordinate, y - coordinate)
使用錨標籤滾動到頁面頂部
單擊連結時,錨點標籤將引用頁面的參考來開啟。如果我們將 #
作為 href
屬性的值傳遞,它將滾動到頁面頂部。
<a href="#"> Top of Page </a>
使用 jQuery 的 scrollTo()
函式滾動到頁面頂部
scrollTo()
函式可幫助我們獲取/操縱 HTML 元素的垂直滾動條位置。它需要一個引數,即 scrollTo()
的位置。通過將其應用於 window 屬性並將位置引數設定為 0
,我們可以使用此函式到達頁面頂部。
$(window).scrollTop(0);
作者: Harshit Jindal
Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.
LinkedIn