<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function New(aClass,aParams)
{
function new_()
{
aClass.Create.apply(this,aParams);
}
new_.prototype=aClass;
return new new_();
}
function Bind(obj,fun)
{
return function()
{
return fun.call(obj);
}
}
function BindAsListener(obj,fun)
{
return function(event)
{
return fun.apply(obj, [event?event:window.event]);
}
}
function AddEventHander(obj,oEventType,fun)
{
if(obj.addEventListener)
{
obj.addEventListener(oEventType,fun,false);
}
else if(obj.attachEvent)
{
obj.attachEvent("on"+oEventType,fun);
}
else
{
obj["on"+oEventType]=fun;
}
}
function RemoveEventHandler(obj, oEventType, fun)
{
if (obj.removeEventListener)
{
obj.removeEventListener(oEventType, fun, false);
}
else if (obj.detachEvent)
{
obj.detachEvent("on" + oEventType, fun);
}
else
{
obj["on" + oEventType] = null;
}
}
var Drag=
{
Create:function(op,id)
{
this._drag=document.createElement("div");
this._drag.id=id;
this._x=this._y=0;//鼠标第一次down时的距离拖动对象的边距
this.SetCss(op);
//添加拖动对象到页面
document.body.appendChild(this._drag);
this._fM=BindAsListener(this,this.Move);
this._fS=Bind(this,this.Stop);
//绑定到document的mousedown事件
AddEventHander(document,"mousedown",BindAsListener(this,this.Start));
},
SetCss:function(options)
{
for(var key in options)
{
this._drag.style[key]=options[key];
}
},
Start:function(ev)
{
this._x=ev.clientX-this._drag.offsetLeft;
this._y=ev.clientY-this._drag.offsetTop;
AddEventHander(document,"mousemove",this._fM);
AddEventHander(document,"mouseup",this._fS);
},
Move:function(ev)
{
this._drag.style.left=ev.clientX-this._x;
this._drag.style.top=ev.clientY-this._y;
},
Stop:function()
{
RemoveEventHandler(document,"mousemove",this._fM);
RemoveEventHandler(document,"mouseup",this._fS);
}
}
</script>
</head>
<body>
<script type="text/javascript">
var op={width:"40px",height:"40px",border:"1px solid #ccc",background:"#E5F5FF",position:"absolute"};
var d=New(Drag,[op,"MyDrag"]);
</script>
</body>
</html>