方法一:使用錨標記
這是最簡單粗暴的一種方法,具體如下:
頁面頂部放置代碼:
<a id="backtop"></a>
頁面底部放置代碼:
<a href="#backtop">返回頂部</a>
方法二、使用JS 監控scrollTop
關鍵點:
1.當滾動條滾動的距離超過設定值時,顯現回到頂部按鈕。
2.點擊按鈕後,觸發定時器,使scrollTop值緩速減小,從而實現回到頂部。
當然,可以讓scrollTop值直接爲0,這個看自己的需求。
下面是一個例子:
HTML
<body style="height: 3000px;">//增加body寬度,使其出現滾動條
<div id="backTop" class="backTop"></div>//創建回到頂部的按鈕
</body>
CSS
<style>
.backTop{
width: 50px;
height: 50px;
background-color: hotpink;
position: fixed;
bottom: 10%;
right: 20px;
display: none;
}
</style>
JS
<script>
window.onload=function(){
//獲取div
var oBackTop = document.getElementById("backTop")
//保存可視窗口的高度
var iWindowLength = document.documentElement.clientHeight
//保存定時器
var timer = null
//元素滾動事件
document.onscroll = function() {
//滾動時,獲取滾輪滾動的距離
var iRollingLength = document.documentElement.scrollTop
//判斷滾動距離是否大於窗口高度,是則顯現div
if(iRollingLength>iWindowLength){
oBackTop.style.display="block"
}else{
oBackTop.style.display="none"
}
//滾動距離到0時,即已經回到頂部,則關閉定時器
if(iRollingLength == 0){
clearInterval(timer)
}
}
//沒有回到頂部之前,若用戶觸發了滾輪事件,關閉定時器
document.onwheel=function(){
clearInterval(timer)
}
//點擊div時,觸發定時器,使滾動距離緩速減小
oBackTop.onclick=function(){
timer = setInterval(function(){
document.documentElement.scrollTop = document.documentElement.scrollTop/1.07
},10)
}
}
</script>
至此,回到頂部的效果就算完成了,奇怪的是,除了比錨的方法多了一個緩衝運動,代碼卻是多了一大堆(怪我寫的太麻煩^^)!
不久,在查閱文檔後,發現了更簡單的方法(有兼容問題):
方法三、API :Element.scrollIntoView()
該方法的文檔介紹:https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView
Element.scrollIntoView()
該方法可以讓當前的元素滾動到瀏覽器窗口的可視區域內。
參數
1.alignToTop
一個Boolean值:
如果爲true,元素的頂端將和其所在滾動區的可視區域的頂端對齊。
如果爲false,元素的底端將和其所在滾動區的可視區域的底端對齊。
2.behavior
定義動畫過渡效果, "auto"或 “smooth” 之一。默認爲 “auto”。
3.block
定義垂直方向的對齊, “start”, “center”, “end”, 或 "nearest"之一。默認爲 “start”。
4、inline
定義水平方向的對齊, “start”, “center”, “end”, 或 "nearest"之一。默認爲 “nearest”。
有了這個方法,優化一下方法二的代碼,這次只用改變JS代碼就好了,如下:
JS
<script>
window.onload=function(){
var oBackTop = document.getElementById("backTop")
var iWindowLength = document.documentElement.clientHeight
document.onscroll = function() {
var iRollingLength = document.documentElement.scrollTop
if(iRollingLength>iWindowLength){
oBackTop.style.display="block"
}else{
oBackTop.style.display="none"
}
}
oBackTop.onclick=function(){
//關鍵就在這一段,定義緩衝的過渡效果就好了
document.body.scrollIntoView({behavior: 'smooth'})
}
}
</script>
與方法二對比,省了不少代碼!
———————————————————————————————————————————————————
結語:若文章有錯誤的地方,煩請在評論區指出。當然,我會不定時的重新編輯寫過的文章,查錯及優化,希望能將最好的文章展現給讀者。