DIV CSS 佈局教程網

JS 判斷滾動條是否到達頁面頂部或底部的完整方案
編輯:關於JavaScript     

我們常在很多網站看到「返回頂部」的效果:當滾動條滾到一定位置時按鈕出現,否則自動隱藏。本文將詳細介紹這類效果的實現原理,並給出兼容多瀏覽器的完整代碼。

判斷是否出現滾動條

當可視區域小於頁面實際高度時,即判定出現了滾動條:

if (document.documentElement.clientHeight < document.documentElement.offsetHeight) scroll = true;

要使用 document.documentElement,需要在頁面頭部加入 DOCTYPE 聲明:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

不過這段代碼其實並不嚴謹,因為它沒考慮瀏覽器邊框。offsetHeight 包含了瀏覽器邊框(上下各 2 像素),導致任何情況下 clientHeight 都會小於 offsetHeight,即使沒有滾動條也會誤判為 true。修正方法是減去 4 個像素:

if (document.documentElement.clientHeight < document.documentElement.offsetHeight-4){
  // 執行相關腳本
}

另外要注意,上面判斷的是橫向滾動條;我們通常更關心縱向滾動,對應代碼為:

if (document.documentElement.clientWidth < document.documentElement.offsetWidth-4){
  // 執行相關腳本
}

判斷是否已到達頁面底部

window.onscroll = function (){
  var marginBot = 0;
  if (document.documentElement.scrollTop){
    marginBot = document.documentElement.scrollHeight - (document.documentElement.scrollTop+document.body.scrollTop) - document.documentElement.clientHeight;
  } else {
    marginBot = document.body.scrollHeight - document.body.scrollTop - document.body.clientHeight;
  }
  if(marginBot <= 0) {
    // do something
  }
}

兼容性更好的封裝方案

下面這組工具函數兼容性不錯,可以分別獲取滾動高度、可視高度與文檔實際高度:

// 取窗口滾動條高度
function getScrollTop()
{
  var scrollTop=0;
  if(document.documentElement && document.documentElement.scrollTop)
  {
    scrollTop=document.documentElement.scrollTop;
  }
  else if(document.body)
  {
    scrollTop=document.body.scrollTop;
  }
  return scrollTop;
}

// 取窗口可視範圍的高度
function getClientHeight()
{
  var clientHeight=0;
  if(document.body.clientHeight && document.documentElement.clientHeight)
  {
    clientHeight = (document.body.clientHeight<document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
  }
  else
  {
    clientHeight = (document.body.clientHeight>document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
  }
  return clientHeight;
}

// 取文檔內容實際高度
function getScrollHeight()
{
  return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight);
}

function test(){
  if (getScrollTop()+getClientHeight()==getScrollHeight()){
    alert("到達底部");
  }else{
    alert("沒有到達底部");
  }
}

各瀏覽器的屬性差異

已聲明 DTD 時:

IE / Firefox:document.documentElement.scrollTop 為滾動部分高度,document.body.scrollTop 始終為 0;clientHeight 為可視高度。

Chrome:document.documentElement.scrollTop 始終為 0,document.body.scrollTop 為滾動部分高度。

未聲明 DTD 時:各瀏覽器的 documentElement 與 body 行為會互換,需要格外注意。

其中「瀏覽器所有內容高度」指整個框架的高度,包含滾動部分、可視部分與底部隱藏部分的總和;「滾動部分高度」則是可視頂端距離對象頂端的距離。理解這些屬性差異後,就能寫出兼容 IE、Firefox、Chrome 的滾動效果了。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved