发现之前写的一段ELEMENT拖动代码,惭愧啊!

先看看大师的写法。通过监听document的事件冒泡,来确定可拖动的元素。

var DragDrop = function(){

	var dragging = null;
	var diffX = 0;
	var diffY = 0;

	function handleEvent(event){
		event = EventUtil.getEvent(event);
		var target = EventUtil.getTarget(event);
		switch(event.type){
			case "mousedown":
			if(target.className.indexOf("draggable") > -1){
				dragging = target;
				dragging.style.position = "absolute";
				diffX = event.clientX - target.offsetLeft;
				diffY = event.clientY - target.offsetTop;
			}
			break;
		case "mousemove":
			if(dragging !== null){
				event = EventUtil.getEvent(event);

				dragging.style.left = (event.clientX - diffX) + "px";
				dragging.style.top = (event.clientY - diffY) + "px";
			}
			break;
		case "mouseup":
			dragging = null;
			break;
	}
};
return {
	enable:function(){
		EventUtil.addHandler(document,"mousedown",handleEvent);
		EventUtil.addHandler(document,"mousemove",handleEvent);
		EventUtil.addHandler(document,"mouseup",handleEvent);
	},
	disable:function(){
		EventUtil.removeHandler(document,"mousedown",handleEvent);
		EventUtil.removeHandler(document,"mousemove",handleEvent);
		EventUtil.removeHandler(document,"mouseup",handleEvent);
		}
	}
}();

然后对比一下自己的代码:单一的逐个元素添加,并且貌似没有回收对象。一旦界面上可拖动的元素过多,后果不堪设想。

(function(){
	var drag = function(domElementID){
		if(document.getElementById(domElementID)){
			var target = document.getElementById(domElementID);
			var diffx=diffy=0;
			var canDrag = false;
			target.onmousedown = function(event){
				canDrag = true;
				var evt = event || window.event;
				var obj = event.target || event.srcElement;
				diffx = evt.clientX - obj.offsetLeft;
				diffy = evt.clientY - obj.offsetTop;
			}
			target.onmousemove = function(event){
				if(!canDrag)
					return false;
				var evt = event || window.event;
				var obj = event.target || event.srcElement;
				obj.style.position = "absolute";
				obj.style.left = (evt.clientX - diffx) + "px";
				obj.style.top = (evt.clientY - diffy) + "px";

			}
			target.onmouseup  = function(){
				diffx=diffy=0;
				canDrag = false;
			}
		}

	}
	window.drag = drag;
})();

發表回覆

你的電郵地址並不會被公開。 必要欄位標記為 *