萬盛學電腦網

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

JavaScript 座標體系完整指南:client/offset/screen/page、getBoundingClientRect、元素可見性檢測與滾動同步

準確掌握滑鼠與元素在不同座標系中的位置,是實現拖拽、彈窗定位、懸浮提示、視口檢測、虛擬滾動的基石。本文系統梳理 5 大座標系、getBoundingClientRect 核心方法、跨瀏覽器兼容、滾動容器影響、元素可見性判斷算法。

五大座標系對比

座標系屬性參考原點隨滾動變化典型用途
螢幕screenX/Y顯示器左上角否多螢幕定位、系統級交互
視窗/可視區clientX/Y瀏覽器可視區左上角否彈窗定位、滑鼠跟隨、命中測試
頁面/文件pageX/Y文件左上角是絕對定位元素、拖拽計算、圖表交互
元素內部offsetX/Y、layerX/Y目標元素 padding box 左上角否Canvas 繪圖、圖片裁剪、內部命中測試
元素邊界getBoundingClientRect()視窗左上角是(相對視窗固定)元素精確幾何、碰撞、動畫終點

核心方法:getBoundingClientRect()

const rect = el.getBoundingClientRect();
// 返回 DOMRect: {x, y, top, left, right, bottom, width, height}
// x/y 別名為 left/top
// 相對視窗,含 transform 縮放/旋轉後的最終幾何位置

頁面座標轉換工具函數

// 視窗座標 -> 頁面座標
const clientToPage = (clientX, clientY) => ({
  x: clientX + window.scrollX,
  y: clientY + window.scrollY
});

// 頁面座標 -> 視窗座標
const pageToClient = (pageX, pageY) => ({
  x: pageX - window.scrollX,
  y: pageY - window.scrollY
});

// 獲取元素相對頁面左上角(含滾動容器)
function getPageRect(el) {
  const rect = el.getBoundingClientRect();
  return {
    top: rect.top + window.scrollY,
    left: rect.left + window.scrollX,
    width: rect.width,
    height: rect.height
  };
}

滾動容器影響

若元素在可滾動容器(overflow:auto/scroll)中,getBoundingClientRect 仍相對**視窗**,但元素可見區域受容器裁剪。需結合 element.scrollTop/Left 計算容器內相對位置。

元素可見性檢測

// 簡易版:是否與視窗相交
function isVisible(el) {
  const rect = el.getBoundingClientRect();
  return rect.bottom > 0 && rect.right > 0 &&
         rect.top < window.innerHeight && rect.left < window.innerWidth;
}

// 精確版:IntersectionObserver(推薦,異步、高效能)
const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      console.log('進入視口', entry.target);
      // 懶加載圖片、觸發動畫、曝光埋點
    }
  });
}, { threshold: 0.1, rootMargin: '100px' }); // 提前 100px 觸發

observer.observe(document.querySelector('.lazy-img'));

滾動同步:固定元素跟隨滾動

function stickTo(el, target) {
  const update = () => {
    const rect = target.getBoundingClientRect();
    Object.assign(el.style, {
      position: 'fixed',
      left: rect.left + 'px',
      top: rect.bottom + 8 + 'px',
      width: rect.width + 'px'
    });
  };
  window.addEventListener('scroll', update, { passive: true });
  window.addEventListener('resize', update);
  update();
  return () => { window.removeEventListener('scroll', update); window.removeEventListener('resize', update); };
}
copyright © 萬盛學電腦網 all rights reserved