DIV CSS 佈局教程網

JavaScript 定位實例:讓方塊依選擇移動到指定元素旁
編輯:關於JavaScript     

要動態擺放一個元素,用 JavaScript 讀取目標位置再套上是相當直覺的做法。這個小範例讓使用者輸入 A、B、C,頁面上那個黃色小方塊就會移動到對應元素的座標。

<!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>

幾個重點:

核心只有 positionObject() 這一支函式,用 getBoundingClientRect() 取回目標元素的 left 與 top,再回傳成陣列供呼叫端使用。

要移動的元素必須是 position:absolute(或 fixed),靜態定位下設定 top/left 是沒有作用的,這是初學時最常卡住的一點。

另外要注意座標系統的一致性:getBoundingClientRect() 給的是「相對於視埠」的座標,而 absolute 定位是相對於「最近的定位祖先元素」。若頁面上有捲動或存在 position:relative 的容器,兩者就會對不齊,需要加上 window.scrollX/scrollY 或扣除容器本身的 getBoundingClientRect() 才能得到正確結果。範例中改用 cursor.style.top = pos[1] + 'px' 也比 setAttribute("style", ...) 來得安全,後者會直接覆蓋掉元素原有的所有行內樣式。

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