一,使用 scrollbar 滾動條 (使用錨點的方式)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>點擊回到頁面頂端</title> </head> <body style="height:2000px;"> <button id="test" style="position:fixed;right:0;bottom:0">回到頂部</button> <script> test.onclick = function(){ document.body.scrollTop = document.documentElement.scrollTop = 0; } </script> </body> </html>
二,scrollTop:scrollTop屬性表示被隱藏在內容區域上方的像素數。元素未滾動時,scrollTop的值為0,如果元素被垂直滾動了,scrollTop的值大於0,且表示元素上方不可見內容的像素寬度
由於scrollTop是可寫的,可以利用scrollTop來實現回到頂部的功能
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>點擊回到頁面頂端</title> </head> <body style="height:2000px;"> <button id="test" style="position:fixed;right:0;bottom:0">回到頂部</button> <script> test.onclick = function(){ document.body.scrollTop = document.documentElement.scrollTop = 0; } </script> </body> </html>
三,scrollBy():scrollBy(x,y)方法滾動當前window中顯示的文檔,x和y指定滾動的相對量,只要把當前頁面的滾動長度作為參數,逆向滾動,則可以實現回到頂部的效果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>點擊回到頁面頂端</title> </head> <body style="height:2000px;"> <button id="test" style="position:fixed;right:0;bottom:0">回到頂部</button> <script> test.onclick = function(){ var top = document.body.scrollTop || document.documentElement.scrollTop; scrollBy(0,-top); } </script> </body> </html>