前端開發中頻繁需要獲取元素位置:相對父元素定位(用於彈窗、下拉菜單定位)、相對文檔定位(用於錨點跳轉、拖拽、曝光埋點)。jQuery 提供 .position() 和 .offset() 兩個核心方法,看似相似實則應用場景截然不同。本文深度解析兩者差異、坐標系原理、常見坑點與最佳實踐。
| 方法 | 參考系 | 返回值 | 典型用途 |
|---|---|---|---|
.position() | **最近的定位祖先元素**(position !== static) | { top, left } 數值,單位像素 | 彈窗相對容器居中、下拉菜單定位、拖拽限制邊界 |
.offset() | **文檔根節點** (<html>) | { top, left } 數值,單位像素 | 頁面錨點跳轉、元素曝光判斷、全局座標計算、跨 iframe 定位 |
<div id="parent" style="position: relative; left: 50px; top: 100px; padding: 20px; border: 5px solid red;">
<div id="child" style="margin: 10px; padding: 10px; border: 2px solid blue;">Child</div>
</div>
<script>
const $child = $('#child');
// 相對定位父元素 (#parent) 的偏移
// 包含:parent 的 padding (20) + child 的 margin (10) = 30px
const pos = $child.position();
console.log(pos); // { top: 30, left: 30 }
// 相對文檔的絕對偏移
// 包含:parent 的 left(50) + top(100) + border(5) + padding(20) + child 的 margin(10) = 85px
const off = $child.offset();
console.log(off); // { top: 185, left: 85 } (視 body margin 而定)
// 獲取單個值
const left = $child.position().left;
const top = $child.offset().top;
</script>
文檔 (document)
└── body (margin: 8px)
└── #parent (position:relative; left:50; top:100; border:5px; padding:20)
├── border-box: 50,100 到 50+寬, 100+高
├── padding-box: 55,105 到 ...
└── content-box: 75,125 到 ...
└── #child (margin:10)
├── margin-box: 85,135 ← offset() 參考點
├── border-box: 95,145
└── content-box: 105,155 ← position() 參考點 (相對 parent padding-box)
function centerModal($modal) {
const winW = $(window).width();
const winH = $(window).height();
const scrollTop = $(window).scrollTop();
const scrollLeft = $(window).scrollLeft();
const modalW = $modal.outerWidth();
const modalH = $modal.outerHeight();
$modal.css({
position: 'fixed', // 相對視口固定,不隨滾動
top: scrollTop + (winH - modalH) / 2,
left: scrollLeft + (winW - modalW) / 2,
zIndex: 9999
});
}
// 現代寫法:CSS transform 居中更簡潔
// .modal { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); }
$('.dropdown-toggle').click(function() {
const $btn = $(this);
const $menu = $btn.siblings('.dropdown-menu');
// 方案 A: position() - 要求父容器 position:relative
const pos = $btn.position();
$menu.css({ top: pos.top + $btn.outerHeight(), left: pos.left });
// 方案 B: offset() + 父容器 offset 相減 - 更健壯,不依賴父元素定位
const btnOff = $btn.offset();
const parentOff = $btn.offsetParent().offset();
$menu.css({
top: btnOff.top - parentOff.top + $btn.outerHeight(),
left: btnOff.left - parentOff.left
});
});
function isElementInViewport($el, threshold = 0.5) {
const rect = $el[0].getBoundingClientRect(); // 相對視口
const elH = rect.height;
const visibleH = Math.min(rect.bottom, window.innerHeight) - Math.max(rect.top, 0);
return visibleH / elH >= threshold;
}
// 滾動檢測
$(window).on('scroll', throttle(() => {
$('.track-exposure').each(function() {
if (isElementInViewport($(this)) && !$(this).data('exposed')) {
$(this).data('exposed', true);
trackEvent('exposure', $(this).data('item-id'));
}
});
}, 200));
border 會增加 offset 值。transform / filter / perspective 會改變定位上下文,導致 offset() 計算異常(相對最近的 transform 祖先而非文檔)。getBoundingClientRect() + window.scrollX/Y 手動計算,或確保無 transform 祖先。position: relative/absolute/fixed),offsetParent 為 <body> 或 <html>,此時 position() ≈ offset()(扣除 body margin)。table、td、th 在某些瀏覽器中會成為 offsetParent,導致計算偏差。// 錯誤:隱藏狀態下獲取位置
$('#hidden').show().offset(); // 必須先顯示
// 正確:臨時顯示獲取後隱藏(或用 visibility:hidden + position:absolute 移出視口)
function getHiddenOffset($el) {
const wasHidden = $el.is(':hidden');
if (wasHidden) {
$el.css({ visibility: 'hidden', display: 'block', position: 'absolute' });
}
const off = $el.offset();
if (wasHidden) {
$el.css({ visibility: '', display: '', position: '' });
}
return off;
}
父頁面無法直接獲取 iframe 內元素的文檔座標,需雙方協作通過 postMessage 傳遞 getBoundingClientRect() 結果。
// 相對文檔
function getOffset(el) {
const rect = el.getBoundingClientRect();
return {
top: rect.top + window.scrollY,
left: rect.left + window.scrollX
};
}
// 相對最近定位祖先
function getPosition(el) {
// 簡易版:找到 offsetParent 並遞歸累加
let top = 0, left = 0;
let current = el;
while (current && current !== document.body) {
top += current.offsetTop;
left += current.offsetLeft;
current = current.offsetParent;
}
return { top, left };
// 注意:此簡易版未處理 border、scroll、transform 等複雜情況
// 生產環境建議用 getBoundingClientRect() 方案
}
getBoundingClientRect() + scrollX/Y 獲取文檔座標,配合 CSS transform 實現居中/定位,減少 JS 計算。掌握坐標系本質,定位不再靠猜。