DIV CSS 佈局教程網

JS 打造可拖曳、可關閉的彈跳視窗完整範例
編輯:關於JavaScript     

彈跳視窗加上拖曳與關閉功能,是很典型的 JavaScript 練習題。它同時涵蓋了元素定位、滑鼠事件、事件冒泡攔截與邊界計算,寫完之後對滑鼠互動的掌握會踏實很多。下面是一個可直接存成單一 HTML 檔執行的完整實作。

結構與樣式

視窗先用 display:none 藏起來,透過按鈕喚出;標題列 h2 當作拖曳把手,因此加上 cursor:move:

html, body { height: 100%; overflow: hidden; }
body, div, h2 { margin: 0; padding: 0; }
body { font: 12px/1.5 Tahoma; }
center { padding-top: 10px; }
button { cursor: pointer; }
#win {
  position: absolute;
  top: 50%; left: 50%;
  width: 400px; height: 200px;
  background: #fff;
  border: 4px solid #f90;
  margin: -102px 0 0 -202px;
  display: none;
}
h2 {
  font-size: 12px; height: 18px; text-align: right;
  background: #FC0; border-bottom: 3px solid #f90;
  padding: 5px; cursor: move;
}
h2 span {
  color: #f90; cursor: pointer;
  background: #fff; border: 1px solid #f90; padding: 0 2px;
}

拖曳邏輯

拖曳的標準三步驟是:在 mousedown 時記錄滑鼠與元素左上角的偏移量,在 mousemove 時用滑鼠座標減去偏移量得到新位置,在 mouseup 時解除綁定。這裡額外做了邊界夾制,讓視窗不會被拖出畫面:

window.onload = function () {
  var oWin = document.getElementById("win");
  var oBtn = document.getElementsByTagName("button")[0];
  var oClose = document.getElementById("close");
  var oH2 = oWin.getElementsByTagName("h2")[0];
  var bDrag = false;
  var disX = disY = 0;

  oBtn.onclick = function () {
    oWin.style.display = "block";
  };

  oClose.onclick = function () {
    oWin.style.display = "none";
  };

  // 攔下事件,避免按下關閉鈕時誤觸拖曳
  oClose.onmousedown = function (event) {
    (event || window.event).cancelBubble = true;
  };

  oH2.onmousedown = function (event) {
    var event = event || window.event;
    bDrag = true;
    disX = event.clientX - oWin.offsetLeft;
    disY = event.clientY - oWin.offsetTop;
    this.setCapture && this.setCapture();
    return false;
  };

  document.onmousemove = function (event) {
    if (!bDrag) return;
    var event = event || window.event;
    var iL = event.clientX - disX;
    var iT = event.clientY - disY;
    var maxL = document.documentElement.clientWidth - oWin.offsetWidth;
    var maxT = document.documentElement.clientHeight - oWin.offsetHeight;

    // 上下左右四個方向都做夾制
    iL = iL < 0 ? 0 : iL;
    iL = iL > maxL ? maxL : iL;
    iT = iT < 0 ? 0 : iT;
    iT = iT > maxT ? maxT : iT;

    oWin.style.marginTop = oWin.style.marginLeft = 0;
    oWin.style.left = iL + "px";
    oWin.style.top = iT + "px";
    return false;
  };

  document.onmouseup = window.onblur = oH2.onlosecapture = function () {
    bDrag = false;
    oH2.releaseCapture && oH2.releaseCapture();
  };
};

三個容易踩到的細節

第一,關閉鈕的 onmousedown 必須回傳 cancelBubble,否則按關閉鈕會被判定成開始拖曳。第二,初始置中是用負 margin 折抵寬高的一半,一旦開始拖曳就要把 margin 歸零,改以 left、top 定位,這段程式已經處理過了。第三,把 mouseup 同時綁到 window.onblur 與 onlosecapture,是為了處理滑鼠拖到視窗外才放手、或視窗失焦導致 bDrag 卡在 true 的狀況。

HTML 主體非常精簡:

<div id="win"><h2><span id="close">×</span></h2></div>
<center><button>彈出層</button></center>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved