DIV CSS 佈局教程網

用 JS 實作滑鼠拖曳 div 的效果
編輯:JavaScript綜合知識     

模擬視窗般「按住標題列拖曳」的效果,其實不難,關鍵在計算滑鼠位置與元素初始位置的偏移量,再在移動時套用。以下示範完整做法。

JavaScript

var posX;
var posY;
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,否則會出問題 -->
  <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; }

核心觀念:onmousedown 時記下滑鼠與元素左上角的位置差(offsetX/Y),onmousemove 時用目前滑鼠座標減去這個偏移,即得元素該有的新座標;onmouseup 則解除移動事件。記得讓 divBody 使用 position:relative 並設定初始 left/top,拖曳才會正常。

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