DIV CSS 佈局教程網

用 JavaScript 取得視窗、文件與螢幕的各種尺寸
編輯:JavaScript綜合知識     

做響應式版面或捲動效果時,往往需要知道目前視窗、文件與螢幕的實際尺寸。以下這個函式把常用屬性一次印出來,可以當成對照表使用。

function getInfo() {
  var s = "";
  s += " 網頁可見區域寬:" + document.body.clientWidth + " ";
  s += " 網頁可見區域高:" + document.body.clientHeight + " ";
  s += " 網頁可見區域寬:" + document.body.offsetWidth + "(含邊線與捲軸) ";
  s += " 網頁可見區域高:" + document.body.offsetHeight + "(含邊線) ";
  s += " 網頁正文全文寬:" + document.body.scrollWidth + " ";
  s += " 網頁正文全文高:" + document.body.scrollHeight + " ";
  s += " 網頁被捲去的高(ff):" + document.body.scrollTop + " ";
  s += " 網頁被捲去的高(ie):" + document.documentElement.scrollTop + " ";
  s += " 網頁被捲去的左:" + document.body.scrollLeft + " ";
  s += " 網頁正文部分上:" + window.screenTop + " ";
  s += " 網頁正文部分左:" + window.screenLeft + " ";
  s += " 螢幕解析度的高:" + window.screen.height + " ";
  s += " 螢幕解析度的寬:" + window.screen.width + " ";
  s += " 螢幕可用工作區高:" + window.screen.availHeight + " ";
  s += " 螢幕可用工作區寬:" + window.screen.availWidth + " ";
  s += " 色彩深度:" + window.screen.colorDepth + " 位彩色 ";
  s += " 裝置 DPI:" + window.screen.deviceXDPI + " 像素/英寸 ";
  s += " window 頁面可視部分高度(ff):" + window.innerHeight + " ";
  alert(s);
}

幾個容易混淆的概念

  • clientWidth/clientHeight:可視區域尺寸,不含邊框與捲軸
  • offsetWidth/offsetHeight:含邊框與捲軸的實際佔用尺寸
  • scrollWidth/scrollHeight:內容的完整尺寸,含被捲軸遮住而看不到的部分
  • scrollTop/scrollLeft:目前已被捲掉的距離
  • screen.width/height:螢幕實體解析度;availWidth/availHeight 扣掉工作列等系統 UI 後的可用區域

要注意的是,在標準模式下真正可靠的取值來源是 document.documentElement,而 body 的 clientWidth 在怪異模式下才代表視窗寬度。deviceXDPI 是 IE 專屬屬性,其他瀏覽器需改用 window.devicePixelRatio。實務上若要取得視窗尺寸,直接讀 window.innerWidth/innerHeight 通常最單純。

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