核心 API 對比
| 方法 | 返回值 | 參考基準 | 適用場景 |
.offset() |
{ top, left } |
文檔 |
彈窗定位、拖拽、全局座標計算 |
.position() |
{ top, left } |
最近的定位祖先 |
相對容器內定位、動畫起點計算 |
基礎用法
// 絕對位置 (相對文檔)
var offset = $('#element').offset();
console.log('X:', offset.left, 'Y:', offset.top);
// 相對位置 (相對 offsetParent)
var position = $('#element').position();
console.log('相對 X:', position.left, '相對 Y:', position.top);
原理深度解析
offset() 內部實現邏輯
- 獲取元素
getBoundingClientRect():相對視口座標
- 加上文檔滾動偏移:
window.scrollX / scrollY (或 documentElement.scrollLeft/Top)
- 減去
clientTop/Left (邊框寬度) 獲取內容區左上角
- 處理
fixed 定位元素特殊情況
- 處理
transform 導致的座標系變化 (現代 jQuery 已支援)
position() 內部邏輯
- 獲取元素
offset()
- 獲取
offsetParent 的 offset()
- 相減得到相對偏移
- 再減去
offsetParent 的邊框寬度
實戰場景
場景一:彈窗居中顯示
function centerModal($modal) {
var winW = $(window).width(), winH = $(window).height();
var modW = $modal.outerWidth(), modH = $modal.outerHeight();
$modal.css({
left: (winW - modW) / 2 + $(window).scrollLeft(),
top: (winH - modH) / 2 + $(window).scrollTop()
});
}
場景二:元素跟隨鼠標 Tooltip
$(document).on('mousemove', '.has-tooltip', function(e) {
var $tip = $('#tooltip');
// 以滑鼠位置為基準,微調偏移
$tip.css({
left: e.pageX + 10,
top: e.pageY + 10
}).show();
}).on('mouseleave', '.has-tooltip', function() {
$('#tooltip').hide();
});
場景三:拖拽排序中的位置計算
var $items = $('.sortable-item');
$items.on('mousedown', function(e) {
var $this = $(this);
var startOffset = $this.offset(); // 記錄初始絕對位置
var startX = e.pageX, startY = e.pageY;
$(document).on('mousemove.drag', function(e) {
var dx = e.pageX - startX;
var dy = e.pageY - startY;
// 使用 position() 相對容器移動,避免滾動影響
var pos = $this.position();
$this.css({ left: pos.left + dx, top: pos.top + dy });
}).on('mouseup.drag', function() {
$(document).off('.drag');
});
});
場景四:滾動監測元素進入視口
function isInViewport(el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
// 或用 offset 比較
function isInViewportOffset($el) {
var offset = $el.offset();
var scrollTop = $(window).scrollTop();
var scrollLeft = $(window).scrollLeft();
return offset.top < scrollTop + $(window).height() &&
offset.left < scrollLeft + $(window).width() &&
offset.top + $el.outerHeight() > scrollTop &&
offset.left + $el.outerWidth() > scrollLeft;
}
常見陷阱與避坑
| 陷阱 | 現象 | 解決 |
| 隱藏元素 offset 為 {0,0} |
display:none 導致無幾何信息 |
先 show() 獲取後再 hide(),或用 visibility:hidden |
| transform 導致 offset 偏移 |
CSS transform 創建新座標系 |
jQuery 3.0+ 已修復,舊版需手動計算 matrix |
| iframe 跨域無法獲取 |
安全限制阻止訪問 iframe 內元素 |
同域下用 iframe.contentWindow.$('#el').offset() |
| body 有 margin 導致偏差 |
offset() 相對文檔,body margin 計入 |
CSS reset 歸零 body margin,或手動扣除 |
| 頻繁調用導致重排 |
連續讀寫 offset/position 觸發強制重排 |
緩存讀取值、批量寫入、使用 transform 代替 top/left 動畫 |
原生 JS 替代方案(無依賴)
// 絕對位置 (等同 jQuery offset)
function getOffset(el) {
const rect = el.getBoundingClientRect();
return {
top: rect.top + window.scrollY,
left: rect.left + window.scrollX
};
}
// 相對位置 (等同 jQuery position)
function getPosition(el) {
const parent = el.offsetParent || document.body;
const offset = getOffset(el);
const parentOffset = getOffset(parent);
// 扣除父元素邊框
const parentStyle = getComputedStyle(parent);
return {
top: offset.top - parentOffset.top - parseFloat(parentStyle.borderTopWidth),
left: offset.left - parentOffset.left - parseFloat(parentStyle.borderLeftWidth)
};
}
結語
offset() 與 position() 是 jQuery 定位體系的雙支柱。理解「文檔座標」與「定位父座標」的區別,掌握 getBoundingClientRect + 滾動偏移的核心算法,能讓你在複雜佈局、拖拽、彈窗、視口檢測等場景遊刃有餘。現代項目可直接使用原生 API 替代,減少依賴。