DIV CSS 佈局教程網

JavaScript 元素定位實作:用 getBoundingClientRect 讓游標方塊移動
編輯:關於JavaScript     

要在頁面上「把某個東西搬到另一個元素旁邊」,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>

幾個值得留意的點

  • position 必須是 absolute 或 relative:範例中 #cursor 設為 absolute,top/left 才有意義。若元素是 static,座標設定不會生效。
  • getBoundingClientRect 是相對視窗的:回傳值隨捲動而改變。若頁面會捲動,要加上 document.documentElement.scrollTop/scrollLeft 才是相對文件的座標。
  • 寫 style 時別忘了單位:top 與 left 必須帶 px,少了單位瀏覽器會直接忽略。

這個範例用 prompt 迴圈是為了方便反覆測試,實務上通常會換成點擊事件或拖曳(mousedown/mousemove/mouseup)來驅動。理解座標怎麼取得、怎麼套用,才是這段程式真正的重點。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved