在實現浮動提示、彈出定位、智慧捲動等效果時,往往需要知道某個元素距離視窗上下左右各有多少空間。本文給出一個基於 jQuery 的通用函式。
function getDistance(obj) {
if (!obj instanceof jQuery) {
obj = $(obj);
}
var distance = {};
distance.top = (obj.offset().top - $(document).scrollTop());
distance.bottom = ($(window).height() - distance.top - obj.outerHeight());
distance.left = (obj.offset().left - $(document).scrollLeft());
distance.right = ($(window).width() - distance.left - obj.outerWidth());
return distance;
}
obj.offset() 回傳的是元素相對於文件的座標,它不受滾動影響。減去 `$(document).scrollTop()` 與 `scrollLeft()` 之後,得到的就是元素相對於「當前可見視窗」的座標,也就是 distance.top 與 distance.left。
下邊距與右邊距則用「視窗尺寸減去起始距離與元素自身尺寸」得出:bottom 等於視窗高度減 top 再減元素外部高度;right 同理。使用 outerHeight() 與 outerWidth() 而非 height()/width(),是為了把 padding 與 border 一併計入,這樣算出來的可用空間才準確。
1. 函式回傳的是「元素到視窗四邊的距離」,而不是到文件四邊的距離。若需要文件座標,直接用 offset() 即可,不必減 scroll 值。
2. `!obj instanceof jQuery` 這個判斷的運算優先級有問題——`!` 會先作用於 obj,實際上並不能正確判斷是否為 jQuery 物件。更穩妥的寫法是 `if (!(obj instanceof jQuery))` 加上括號,或直接檢查 `obj.jquery`。
3. 若元素目前是 display:none 狀態,offset() 會回傳 0,需要先讓它參與佈局再取值。
4. 在現代專案中,若只是要拿到元素位置資訊,`element.getBoundingClientRect()` 一行就能取得相對於視窗的 top、bottom、left、right,且為原生 API、無需依賴 jQuery,效能也更好。