拖動是一件非常酷的事情。你點擊某個對象,並按住鼠標不放,將鼠標移動到另一個區域,然後釋放鼠標按鈕將對象放在這裡。
下面是一個簡單的案例:
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; }, // 添加監聽事件 addEvent : function (element, type, handler) { if (element.addEventListener) { element.addEventListener(type, handler, false); } else if (element.attachEvent) { element.attachEvent("on" + type, handler); } }, // 注銷監聽事件 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
以上就是本文的全部內容,希望對大家的學習有所幫助。