準確掌握滑鼠與元素在不同座標系中的位置,是實現拖拽、彈窗定位、懸浮提示、視口檢測、虛擬滾動的基石。本文系統梳理 5 大座標系、getBoundingClientRect 核心方法、跨瀏覽器兼容、滾動容器影響、元素可見性判斷算法。
| 座標系 | 屬性 | 參考原點 | 隨滾動變化 | 典型用途 |
|---|---|---|---|---|
| 螢幕 | screenX/Y | 顯示器左上角 | 否 | 多螢幕定位、系統級交互 |
| 視窗/可視區 | clientX/Y | 瀏覽器可視區左上角 | 否 | 彈窗定位、滑鼠跟隨、命中測試 |
| 頁面/文件 | pageX/Y | 文件左上角 | 是 | 絕對定位元素、拖拽計算、圖表交互 |
| 元素內部 | offsetX/Y、layerX/Y | 目標元素 padding box 左上角 | 否 | Canvas 繪圖、圖片裁剪、內部命中測試 |
| 元素邊界 | 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); };
}