萬盛學電腦網

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

JavaScript 獲取瀏覽器窗口/文檔/螢幕尺寸完整速查表

尺寸屬性全景圖


┌─────────────────────────────────────────────────────────────┐
│                        window (瀏覽器窗口)                     │
│  ┌───────────────────────────────────────────────────────┐  │
│  │                    screen (螢幕)                          │  │
│  │  ┌─────────────────────────────────────────────────┐  │  │
│  │  │              document.documentElement (HTML)       │  │  │
│  │  │  ┌───────────────────────────────────────────┐  │  │  │
│  │  │  │           document.body (BODY)             │  │  │  │
│  │  │  │  ┌─────────────────────────────────────┐  │  │  │  │
│  │  │  │  │       可視區域 (Viewport)            │  │  │  │  │
│  │  │  │  └─────────────────────────────────────┘  │  │  │  │
│  │  │  └───────────────────────────────────────────┘  │  │  │
│  │  └─────────────────────────────────────────────────┘  │  │
│  └───────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘

核心屬性對照表

屬性所屬對象含義含邊框/滾動條典型用途
innerWidth/Heightwindow瀏覽器可視區域寬高(含滾動條)含垂直滾動條響應式斷點、Canvas 全屏
outerWidth/Heightwindow瀏覽器整個窗口寬高(含工具欄、邊框)含全部窗口管理、多窗口布局
clientWidth/HeightElement元素內容區+padding 寬高(無滾動條、無邊框)無元素實際渲染尺寸、佈局計算
offsetWidth/HeightElement元素邊框盒寬高(含 padding+border+滾動條)含元素佔位尺寸、碰撞檢測
scrollWidth/HeightElement元素內容實際寬高(含被滾動隱藏部分)無滾動條判斷是否溢出、內容實際大小
scrollLeft/TopElement元素已滾動距離-滾動位置記錄、無限滾動
screen.width/heightscreen螢幕分辨率-全屏適配、多螢幕檢測
screen.availWidth/Heightscreen螢幕可用工作區(扣除任務欄)-最大化窗口尺寸估算
devicePixelRatiowindow物理像素/邏輯像素比(Retina=2, 3倍屏=3)-高清圖片、Canvas 高 DPI

獲取可視區域尺寸(跨瀏覽器兼容)

function getViewport() {
  // 現代瀏覽器(IE9+)
  if (window.innerWidth !== undefined) {
    return { width: window.innerWidth, height: window.innerHeight };
  }
  
  // IE8- 標準模式
  const doc = document.documentElement;
  if (doc.clientWidth !== undefined) {
    return { width: doc.clientWidth, height: doc.clientHeight };
  }
  
  // 怪異模式
  return { width: document.body.clientWidth, height: document.body.clientHeight };
}

// 簡潔版(現代項目足夠)
const viewport = {
  width: window.innerWidth || document.documentElement.clientWidth,
  height: window.innerHeight || document.documentElement.clientHeight
};

獲取文檔完整尺寸

function getDocumentSize() {
  const doc = document.documentElement;
  const body = document.body;
  
  return {
    width: Math.max(
      doc.scrollWidth, doc.clientWidth, body.scrollWidth, body.clientWidth
    ),
    height: Math.max(
      doc.scrollHeight, doc.clientHeight, body.scrollHeight, body.clientHeight
    )
  };
}

元素尺寸與位置獲取

function getElementMetrics(el) {
  const rect = el.getBoundingClientRect(); // 相對視口
  const style = getComputedStyle(el);
  
  return {
    // 尺寸
    width: rect.width,           // 含 padding+border
    height: rect.height,
    clientWidth: el.clientWidth, // 內容+padding
    clientHeight: el.clientHeight,
    offsetWidth: el.offsetWidth, // 含 border+滾動條
    offsetHeight: el.offsetHeight,
    scrollWidth: el.scrollWidth, // 內容實際
    scrollHeight: el.scrollHeight,
    
    // 位置(相對視口)
    top: rect.top,
    left: rect.left,
    right: rect.right,
    bottom: rect.bottom,
    
    // 位置(相對文檔)
    pageTop: rect.top + window.scrollY,
    pageLeft: rect.left + window.scrollX,
    
    // 邊距
    marginTop: parseFloat(style.marginTop),
    marginLeft: parseFloat(style.marginLeft),
    
    // 是否可見
    isVisible: rect.width > 0 && rect.height > 0 && 
               style.visibility !== 'hidden' && style.display !== 'none'
  };
}

滾動位置統一獲取

function getScrollPosition() {
  return {
    x: window.scrollX || window.pageXOffset || document.documentElement.scrollLeft,
    y: window.scrollY || window.pageYOffset || document.documentElement.scrollTop
  };
}

// 滾動到指定位置(平滑)
function scrollTo(x, y, smooth = true) {
  window.scrollTo({ left: x, top: y, behavior: smooth ? 'smooth' : 'auto' });
}

// 元素滾動到可視區
function scrollIntoView(el, align = 'center') {
  el.scrollIntoView({ block: align, inline: 'nearest', behavior: 'smooth' });
}

響應式斷點監聽

// 使用 matchMedia 監聽尺寸變化(優於 resize 事件)
const breakpoints = {
  sm: '(max-width: 575px)',
  md: '(min-width: 576px) and (max-width: 767px)',
  lg: '(min-width: 768px) and (max-width: 991px)',
  xl: '(min-width: 992px) and (max-width: 1199px)',
  xxl: '(min-width: 1200px)'
};

const mediaQueries = Object.entries(breakpoints).map(([name, query]) => ({
  name,
  mql: window.matchMedia(query)
}));

function getCurrentBreakpoint() {
  for (const { name, mql } of mediaQueries) {
    if (mql.matches) return name;
  }
  return 'unknown';
}

// 監聽變化
mediaQueries.forEach(({ name, mql }) => {
  mql.addEventListener('change', e => {
    if (e.matches) {
      console.log('斷點切換至:', name);
      document.documentElement.dataset.breakpoint = name;
    }
  });
});

// 初始化
document.documentElement.dataset.breakpoint = getCurrentBreakpoint();

高 DPI / Retina 屏適配

// Canvas 高清繪製
function setupHiDPICanvas(canvas, width, height) {
  const ratio = window.devicePixelRatio || 1;
  canvas.width = width * ratio;
  canvas.height = height * ratio;
  canvas.style.width = width + 'px';
  canvas.style.height = height + 'px';
  const ctx = canvas.getContext('2d');
  ctx.scale(ratio, ratio);
  return ctx;
}

// 圖片選擇:根據 DPR 載入不同倍圖
function getResponsiveImageUrl(baseUrl, width) {
  const dpr = window.devicePixelRatio || 1;
  const targetWidth = Math.ceil(width * dpr);
  return `${baseUrl}?w=${targetWidth}&dpr=${dpr}`; // 需圖片服務支持
}

常見坑點

  1. zoom 縮放: 瀏覽器縮放時,innerWidth 等返回縮放後的 CSS 像素,非物理像素
  2. 滾動條寬度: Windows 預設 17px,Mac 隱藏滾動條 0px,CSS scrollbar-gutter: stable 可預留空間
  3. iframe 內獲取父窗口: 同源用 parent.innerWidth,跨域需 postMessage 傳遞
  4. 虛擬鍵盤彈出: 移動端視口高度變化,監聽 visualViewport API
copyright © 萬盛學電腦網 all rights reserved