要在頁面上「把某個東西搬到另一個元素旁邊」,JavaScript 提供了相當直接的做法。核心關鍵是 getBoundingClientRect(),它能回傳元素相對於可視區域的位置資訊,我們只要取出 left 與 top,就能拿去設定另一個元素的座標。
下面這個小範例做了三層嵌套的 div(A 包 B、B 包 C),頁面上還有一個黃色小方塊。程式會不斷詢問你想把方塊移到哪一層,輸入 a、b 或 c 即可,方塊就會精準貼到該元素的位置。
function positionObject(obj){
var rect = obj.getBoundingClientRect();
return [rect.left, rect.top];
}回傳的是一個二元素陣列,第一項是水平座標、第二項是垂直座標,後續直接拿去組 style 字串。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>每天一個 JavaScript 實例-操作元素定位元素</title>
<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>
<script>
function positionObject(obj){
var rect = obj.getBoundingClientRect();
return [rect.left, rect.top];
}
window.onload = function(){
var tst = document.documentElement.getBoundingClientRect();
alert(tst.top);
var cont = 'A';
var cursor = document.getElementById("cursor");
while(cont){
cont = prompt("where do you want to move the cursor block?","A");
if(cont){
cont = cont.toLowerCase();
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>
</head>
<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>
</html>這個範例用 prompt 迴圈是為了方便反覆測試,實務上通常會換成點擊事件或拖曳(mousedown/mousemove/mouseup)來驅動。理解座標怎麼取得、怎麼套用,才是這段程式真正的重點。