萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 獲取網頁尺寸屬性完整速查表

核心尺寸屬性對照

屬性意義包含內容
document.body.clientWidth可視區寬度內容 + padding,不含邊框/捲軸
document.body.clientHeight可視區高度內容 + padding,不含邊框/捲軸
document.body.offsetWidth可視區寬度內容 + padding + border + 捲軸
document.body.offsetHeight可視區高度內容 + padding + border
document.body.scrollWidth內容實際寬度含溢出隱藏內容
document.body.scrollHeight內容實際高度含溢出隱藏內容
document.body.scrollTop文件被捲去的高度 (FF/Chrome)—
document.documentElement.scrollTop文件被捲去的高度 (IE/標準模式)—
document.body.scrollLeft文件被捲去的左側距離—
window.screenTop / screenY視窗相對螢幕頂部座標—
window.screenLeft / screenX視窗相對螢幕左側座標—
window.screen.height螢幕解析度高度—
window.screen.width螢幕解析度寬度—
window.screen.availHeight螢幕可用工作區高度扣除工作列
window.screen.availWidth螢幕可用工作區寬度—
window.screen.colorDepth螢幕色深如 24、30
window.screen.deviceXDPI螢幕水平 DPI—
window.innerHeight瀏覽器視窗可視區高度 (含捲軸)標準模式下同 clientHeight
window.innerWidth瀏覽器視窗可視區寬度—

相容性取值最佳實踐

// 文件可視區尺寸(相容標準/怪異模式)
var clientWidth = document.compatMode === 'CSS1Compat' 
  ? document.documentElement.clientWidth 
  : document.body.clientWidth;

var clientHeight = document.compatMode === 'CSS1Compat' 
  ? document.documentElement.clientHeight 
  : document.body.clientHeight;

// 捲動距離(相容)
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;

// 視窗尺寸(現代瀏覽器)
var winWidth = window.innerWidth || document.documentElement.clientWidth;
var winHeight = window.innerHeight || document.documentElement.clientHeight;

實用封裝函式

function getPageDimensions() {
  var d = document, de = d.documentElement, db = d.body;
  var mode = d.compatMode === 'CSS1Compat';
  var root = mode ? de : db;

  return {
    // 視窗可視區
    viewport: { width: de.clientWidth, height: de.clientHeight },
    // 文件總尺寸
    document: { width: de.scrollWidth, height: de.scrollHeight },
    // 捲動位置
    scroll: { top: de.scrollTop || db.scrollTop, left: de.scrollLeft || db.scrollLeft },
    // 螢幕資訊
    screen: { 
      width: screen.width, height: screen.height,
      availWidth: screen.availWidth, availHeight: screen.availHeight,
      colorDepth: screen.colorDepth
    }
  };
}

console.log(getPageDimensions());

視覺化示意

+--------------------------------------------------+  <-- window.screen (螢幕)
| 瀏覽器視窗                                       |
| +--------------------------------------------+  |  <-- window.innerWidth/Height (視窗可視區)
| | 文件內容                                    |  |
| |  (scrollWidth/scrollHeight)                |  |
| |                                            |  |
| |  捲動區域 (scrollTop/scrollLeft)           |  |
| +--------------------------------------------+  |
+--------------------------------------------------+
copyright © 萬盛學電腦網 all rights reserved