如何實現返回頂部的效果

要想解決這個問題須要只要幾個知識點

  1. scrollHeight:元素內容的總高度
  2. scrollWidth:元素內容的總寬度
  3. scrollLeft:由於滾動被隱藏在內容區域上面的高度
  4. scrollTop:由於滾動被隱藏在內容區域左邊的高度

獲取滾動高度的兼容寫法

  1. var scrollHeight = document.documentElement.scrollTop || document.body.scrollTop

獲取瀏覽器視口的大小的兼容寫法

  1. var clientHeight = document.documentElement.clientHeight || document.body.clientHeight

若是滾動高度大於一屏的高度就出現回到頂部

if(scrollHeight > clientHeight){
    //顯示回到頂部按鈕
}else{
    //隱藏回到頂部按鈕
}
複製代碼

點擊回到頂部進行的操做

相關文章
相關標籤/搜索