DIV CSS 佈局教程網

用 JavaScript 實作類 Google 首頁的 Div 拖曳效果
編輯:關於JavaScript     

早期 Google 首頁曾經提供過「自訂版面、拖曳模組位置」的功能。本文拆解它的實作思路:用絕對定位的浮層跟著滑鼠跑,放開時計算落點並插入目標儲存格,最後做一段回彈動畫。

一、基礎工具函式

// 瀏覽器偵測
var ie = false, moz = false;
(function () {
  var userAgent = navigator.userAgent;
  if (userAgent.indexOf("MSIE") != -1) ie = true;
  else if (userAgent.indexOf("Firefox") != -1) moz = true;
})();

// 依 ID 取元素
function $E_ID(idString) { return document.getElementById(idString); }

// 依標籤名取集合
function $Es_Tag(tagName) { return document.getElementsByTagName(tagName); }

二、取得元素的絕對位置

offsetLeft / offsetTop 是相對於 offsetTop 父元素的,所以要沿著 offsetParent 鏈往上累加才是頁面座標:

function $GetInfo(o) {
  var to = { left: 0, right: 0, top: 0, bottom: 0 };
  var twidth = o.offsetWidth, theight = o.offsetHeight;
  while (o) {
    to.left += o.offsetLeft;
    to.top += o.offsetTop;
    o = o.offsetParent;
  }
  to.right = to.left + twidth;
  to.bottom = to.top + theight;
  return to;
}

三、命中測試

判斷滑鼠座標是否落在某元素範圍內,是「放到哪一格」的判斷基礎:

function $hitTest(obj, event) {
  obj = $GetInfo(obj);
  var x = event.clientX, y = event.clientY;
  return (x >= obj.left && x <= obj.right && y >= obj.top && y <= obj.bottom);
}

四、拖曳主體

Drag 建構函式負責三件事:dragStart 建立浮層、onDrag 更新位置並偵測落點、dragEnd 收尾並播放回彈。

function Drag(event) {
  this.dragged = false;
  this.ao = null;      // 被拖的元素
  this.tdiv = null;    // 跟著滑鼠跑的浮層
  this.fixLeft = 0;
  this.fixTop = 0;
  this.lastX = event.clientX;
  this.lastY = event.clientY;

  this.dragStart = function (event) {
    this.ao = ie ? event.srcElement : (moz ? event.target : null);
    if (ie) document.body.onselectstart = function () { return false; }  // 防止選字
    if (moz && this.ao.nodeType == 3) this.ao = this.ao.parentNode;
    if (this.ao.tagName == "TD" || this.ao.tagName == "TR") {
      this.ao = this.ao.offsetParent.parentNode;
    } else { return; }
    if (this.ao.className != "dragdiv") return;

    this.tdiv = $E_ID("tmpdiv");
    this.tdiv.style.visibility = "visible";
    this.tdiv.style.zIndex = 100;
    this.tdiv.innerHTML = this.ao.innerHTML;
    this.tdiv.style.width = this.ao.offsetWidth + "px";
    this.tdiv.style.height = this.ao.offsetHeight + "px";
    this.tdiv.style.top = $GetInfo(this.ao).top + "px";
    this.tdiv.style.left = $GetInfo(this.ao).left + "px";
    // IE 用 filter 控制透明度,其餘用 opacity
    this.tdiv.style.filter = "alpha(opacity=70)";
    if (ie) this.tdiv.filters.alpha.opacity = 70;
    this.tdiv.style.opacity = 0.7;
    this.fixTop = parseInt($GetInfo(this.tdiv).top);
    this.fixLeft = parseInt($GetInfo(this.tdiv).left);
    this.dragged = true;
  };
}

拖曳中要沿著 root 表格的每個儲存格做命中測試,一旦命中就依子節點順序 insertBefore,否則 appendChild:

this.onDrag = function (event) {
  if (!this.dragged || this.ao == null) return;
  var tX = event.clientX, tY = event.clientY;
  this.tdiv.style.left = parseInt(this.fixLeft + tX - this.lastX - document.body.scrollLeft) + "px";
  this.tdiv.style.top = parseInt(this.fixTop + tY - this.lastY - document.body.scrollTop) + "px";
  for (var m = 0; m < $E_ID("root").rows.length; m++) {
    var rootCells = $E_ID("root").rows[m].cells;
    for (var i = 0; i < rootCells.length; i++) {
      if ($hitTest(rootCells[i], event)) {
        rootCells[i].appendChild(this.ao);
        break;
      }
    }
  }
};

五、回彈動畫

放開滑鼠後,浮層要「飛回」到實際落點,同時淡出。做法是把位移與透明度分成固定步數,用 setInterval 逐步逼近:

this.repos = function (aa, ab, obj) {
  var f = ie ? obj.tdiv.filters.alpha.opacity : obj.tdiv.style.opacity * 100;
  var kf = f / ab;
  var tl = parseInt($GetInfo(obj.tdiv).left);
  var tt = parseInt($GetInfo(obj.tdiv).top);
  var kl = (tl - $GetInfo(obj.ao).left) / ab;
  var kt = (tt - $GetInfo(obj.ao).top) / ab;
  return setInterval(function () {
    if (ab < 1) {
      clearInterval(Drag.mm);
      obj.tdiv.style.visibility = "hidden";
      obj.tdiv.style.zIndex = "";
      return;
    }
    ab--;
    tl -= kl; tt -= kt; f -= kf;
    obj.tdiv.style.left = parseInt(tl) + "px";
    obj.tdiv.style.top = parseInt(tt) + "px";
    if (ie) obj.tdiv.filters.alpha.opacity = f;
    else obj.tdiv.style.opacity = f / 100;
  }, aa / ab);
};

六、頁面骨架與事件掛載

body 上掛三個事件就足夠:

<body onMouseDown="init(event)" onMouseMove="move(event)" onMouseUp="end()">
var tDrag = null;
function init(event) { tDrag = new Drag(event); tDrag.dragStart(event); }
function move(event) { if (tDrag != null) tDrag.onDrag(event); }
function end() { if (tDrag != null) { tDrag.dragEnd(); tDrag = null; } }

視覺上需要一個半透明的浮層節點與表格容器:

<script>document.write("<div id='tmpdiv'><\/div>");</script>
<table id="root" style="width:600px;height:300px" cellpadding="0" cellspacing="1">
  <tr><td><div class="dragdiv" id="div1">可移動 DIV1</div></td></tr>
</table>

幾個實作細節

  • 拖曳期間必須關掉文字選取(IE 用 onselectstart 回傳 false),否則會一路選字。
  • Firefox 的 event.target 可能是文字節點,要往上補一層 parentNode。
  • 透明度在 IE 走 filter: alpha(opacity=),其他瀏覽器走 opacity,兩套都要寫。
  • 位置計算要扣掉 document.body.scrollLeft / scrollTop,否則頁面捲動後會偏移。

今天要實作同樣的效果,用 HTML5 的 draggable 屬性加上 dragstart / dragover / drop 事件會簡短很多;但這份程式碼把「座標計算、命中測試、動畫補間」三件事講得很透,讀懂之後再換 API 會很輕鬆。

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