需要把某個元素精確移動到另一個元素的位置上時,用 JS 是個不錯的選擇。這個例子示範如何讀取元素坐標並據此定位一個游標方塊,同時處理了嵌套元素的情況。
<style>
div#a{ width:500px; }
div{ border:1px solid #000; padding:10px; }
#cursor{
position:absolute;
background-color:#ff0;
width:20px;
height:20px;
left:50px;
top:300px;
}
</style>
<body>
<div id="a">
<p>A</p>
<div id ="b">
<p>B</p>
<div id="c">
<p>C</p>
</div>
</div>
</div>
<div id="cursor"></div>
</body>
結構特意做成 A 包含 B、B 包含 C 的三層嵌套,目的就是為了驗證定位函數在嵌套場景下是否依然準確。
<script>
// 返回元素相對於視窗的坐標
function positionObject(obj){
var rect = obj.getBoundingClientRect();
return [rect.left, rect.top];
}
window.onload = function(){
var cursor = document.getElementById("cursor");
var cont = 'A';
while(cont){
cont = prompt("要把方塊移動到哪個元素?","A");
if(cont){
cont = cont.toLowerCase();
// 只接受 a / b / c 三個合法目標
if(cont == "a" || cont == "b" || cont == "c"){
var elem = document.getElementById(cont);
var pos = positionObject(elem);
console.log(pos);
cursor.setAttribute("style",
"top:" + pos[1] + "px;" +
"left:" + pos[0] + "px"
);
}
}
}
}
</script>
getBoundingClientRect() 是這個例子的靈魂。它返回一個包含 left、top、right、bottom、width、height 的對象,全部相對於當前視窗左上角。相比沿著 offsetParent 鏈一層層累加 offsetLeft/offsetTop 的老方法,它一次調用就能拿到最終結果,代碼量與出錯概率都大幅降低。
示例中還寫了 alert(document.documentElement.getBoundingClientRect().top) 這類調試語句,用來驗證返回值是否合理,這種「先打印再使用」的習慣在處理坐標問題時很值得保持。
滾動量必須補償。這是最容易踩的坑。getBoundingClientRect() 給的是視窗坐標,而 position:absolute 的定位依據通常是文檔坐標。頁面一旦滾動,兩者就會產生差值。正確做法是把滾動量加回去:
function getDocumentPosition(obj){
var rect = obj.getBoundingClientRect();
return {
left: rect.left + window.pageXOffset,
top: rect.top + window.pageYOffset
};
}
兼容舊瀏覽器。IE8 及以下不支持 getBoundingClientRect() 返回 width/height,需要用 right - left 自行計算;同時 pageXOffset 要退回到 document.documentElement.scrollLeft。
用具體樣式屬性而非 style 字符串。示例中用 setAttribute("style", ...) 拼接字符串,這種做法會覆蓋元素原有的全部內聯樣式。更安全的寫法是直接操作具體屬性:
cursor.style.left = pos[0] + 'px';
cursor.style.top = pos[1] + 'px';
按需加偏移量。如果希望方塊左上角對齊目標元素的左上角,上面的代碼剛好;但如果希望方塊居中或放在目標右下角,就需要依據 rect.width/height 做相應加減。
如今更推薦直接讓瀏覽器處理定位計算,一次調用搞定滾動、對齊、邊界約束:
document.getElementById('c').scrollIntoView({
behavior: 'smooth',
block: 'center'
});
// 拖拽場景可用 Pointer Events + transform
cursor.style.transform = `translate(${x}px, ${y}px)`;
用 transform 代替 left/top 進行移動,能觸發 GPU 合成層,性能明顯優於觸發重排的屬性修改,在動畫場景中差距尤為明顯。