拖動是一件非常酷的事情叨襟。你點擊某個對象,并按住鼠標不放幔荒,將鼠標移動到另一個區(qū)域糊闽,然后釋放鼠標按鈕將對象放在這里。
下面是一個簡單的案例:
HTML部分:注意爹梁,拖動元素一定要為絕對定義右犹,即position = absolute;
<div style="position:absolute;height:100px;width:100px;background:red" class="draggable"></div>
<script src="dome.js"></script>
JS部分(dome.js):
var EventUtil = {
// 獲取事件和目標
getEvent : function (event) {
return event ? event : window.event;
},
getTarget : function (event) {
return event.target || event.srcElement;
},
// 添加監(jiān)聽事件
addEvent : function (element, type, handler) {
if (element.addEventListener)
{
element.addEventListener(type, handler, false);
} else if (element.attachEvent)
{
element.attachEvent("on" + type, handler);
}
},
// 注銷監(jiān)聽事件
delEvent : function (element, type, handler) {
if (element.removeEventListener)
{
element.removeEventListener(type, handler, false);
} else if (element.detachEvent)
{
element.detachEvent("on" + type, handler);
}
}
}
var DragDrop = function () {
// 判斷DOM元素是否正在被拖動的標志
var dragging = null;
// DOM元素左上角與鼠標指針的差值
diffX = 0;
diffY = 0;
function handleEvent(event) {
event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);
switch (event.type) {
case "mousedown" :
// 判斷DOM元素的class中是否含有draggable屬性
if (target.className.indexOf("draggable") > -1) {
dragging = target;
diffX = event.clientX - target.offsetLeft;
diffY = event.clientY - target.offsetTop;
}
break;
case "mousemove" :
if (dragging != null) {
target.style.left = event.clientX - diffX + "px";
target.style.top = event.clientY - diffY + "px";
}
break;
case "mouseup" :
dragging = null;
break;
}
}
return {
enable : function () {
EventUtil.addEvent(document, "mousedown", handleEvent);
EventUtil.addEvent(document, "mousemove", handleEvent);
EventUtil.addEvent(document, "mouseup", handleEvent);
},
disable : function () {
EventUtil.delEvent(document, "mousedown", handleEvent);
EventUtil.delEvent(document, "mousemove", handleEvent);
EventUtil.delEvent(document, "mouseup", handleEvent);
}
}
}();
DragDrop.enable();
這里需要講解的是diffX和diffY,它們表示元素左上角與鼠標指針的差值卫键。
diffX = 鼠標的x坐標 - 元素對象的offsetLeft
diffY = 鼠標的y坐標 - 元素對象的offsetTop
如下圖所示: