DIV CSS 佈局教程網

用 JS + HTML + CSS 實作可拖曳 DIV:三檔搭配的完整範例
編輯:關於JavaScript     

想讓頁面上的浮層可以被使用者拖著跑?其實原理非常單純:在標題列上監聽 mousedown,記下滑鼠與元素左上角之間的偏移量,接著在 mousemove 中把這個偏移量套回 left / top,最後在 mouseup 時解除監聽即可。

JavaScript

var posX, posY;
var fdiv = document.getElementById("divBody");

document.getElementById("divHead").onmousedown = function(e){
  if (!e) e = window.event;              // 兼容 IE
  posX = e.clientX - parseInt(fdiv.style.left);
  posY = e.clientY - parseInt(fdiv.style.top);
  document.onmousemove = mousemove;
};

document.onmouseup = function(){
  document.onmousemove = null;           // 放開滑鼠就停止拖曳
};

function mousemove(ev){
  if (ev == null) ev = window.event;     // 兼容 IE
  fdiv.style.left = (ev.clientX - posX) + "px";
  fdiv.style.top  = (ev.clientY - posY) + "px";
}

HTML

<div class="divBody" id="divBody" style="left: 29px; top: 14px;">
  <!-- 一定要寫初始的 left / top,否則 parseInt 會得到 NaN -->
  <div class="divHead" id="divHead" style="cursor: move;"></div>
  <div class="content"></div>
  <div class="tail"></div>
</div>

CSS

.divBody{
  border: solid #CCC 1px;
  width: 500px;
  height: 400px;
  position: relative;
  z-index: 0;
  margin-left: auto;
  margin-right: auto;
}
.divHead{ width: 500px; height: 50px; background-color: #CCC; }
.content{ width: 500px; height: 300px; }
.tail{
  background: #CCC; height: 50px; width: 500px;
  display: table-cell; vertical-align: middle;
}

關鍵重點

為什麼 HTML 一定要預先寫上 left 與 top?因為程式用 parseInt(fdiv.style.left) 取初始位置,若樣式中沒有這兩個值,讀到的就是空字串,parseInt 會回傳 NaN,往後的座標計算就全盤失效。

另外,cursor: move 是給使用者的視覺提示,告訴他這塊標題列是可以拖的;把 mousedown 綁在標題列而非整個容器上,也能避免在內容區點選文字時誤觸拖曳。

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