拖拽
// (来自JavaScript高级程序设计) 自定义事件 function EventTarget() { this.handler = {}; } EventTarget.prototype = { constructor: EventTarget, // 添加事件 addHandler: function (type, fn) { if (!this.handler[type]) this.handler[type] = []; this.handler[type].push(fn); }, // 删除事件 removeHandler: function (type) { if (this.handler[type]) delete this.handler[type]; }, // 执行事件 fire: function (event) { if (!event.target) event.target = this; if (Array.isArray(this.handler[event.type])) { var handlers = this.handler[event.type]; for (var i = 0, len = handlers.length; i < len; i ++) { handlers[i](event); } } } }; // 拖拽 var DrapDrop = function () { var dragdrop = new EventTarget(), dragging = null, diffX = 0, diffY = 0; var handlerEvent = function (e) { var e = e || event; var t = e.target || e.srcElement; switch (e.type) { case 'mousedown': if (t.className.indexOf('draggable') >= 0) { diffX = e.clientX - t.offsetLeft; diffY = e.clientY - t.offsetTop; dragging = t; dragdrop.fire({type: 'dragstart', target: dragging, x: e.clientX, y: e.clientY}); } break; case 'mousemove': if (!!dragging) { dragging.style.top = e.clientY - diffY + 'px'; dragging.style.left = e.clientX - diffX + 'px'; dragdrop.fire({type: 'drag', target: dragging, x: e.clientX, y: e.clientY}); } break; case 'mouseup': dragging = null; dragdrop.fire({type: 'dragend', target: t, x: e.clientX, y: e.clientY}); break; } }; // 接口 dragdrop.enable = function () { document.onmousedown = document.onmousemove = document.onmouseup = handlerEvent; }; dragdrop.disable = function () { document.onmousedown = document.onmousemove = document.onmouseup = null; }; return dragdrop; }();