var dragobject={
z: 0,
x: 0,
y: 0,
offsetx : null,
offsety : null,
targetobj : null,
dragapproved : 0,
initialize:function(){
document.onmousedown=this.drag
document.onmouseup=function(){this.dragapproved=0}
},
drag:function(e){
var evtobj=window.event? window.event : e
this.targetobj=window.event? event.srcElement : e.target
if (this.targetobj.className=="drag"){
this.dragapproved=1
if (isNaN(parseInt(this.targetobj.style.left))){this.targetobj.style.left=0}
if (isNaN(parseInt(this.targetobj.style.top))){this.targetobj.style.top=0}
this.offsetx=parseInt(this.targetobj.style.left)
this.offsety=parseInt(this.targetobj.style.top)
this.x=evtobj.clientX
this.y=evtobj.clientY
if (evtobj.preventDefault)
evtobj.preventDefault()
document.onmousemove=dragobject.moveit
}
},
moveit:function(e){
var evtobj=window.event? window.event : e
if (this.dragapproved==1){
this.targetobj.style.left=this.offsetx+evtobj.clientX-this.x+"px"
this.targetobj.style.top=this.offsety+evtobj.clientY-this.y+"px"
return false
}
}
}
dragobject.initialize()
这个我知道,语法我都知道吗,就是逻辑不懂。能不能把这个逻辑帮我理一下?有点迷惑,这个是怎样达到移动DIV这个效果的。
追答drag:function(e){
var evtobj=window.event? window.event : e; //获取对象的事件状态,IE支持window.event, FF是e
this.targetobj=window.event? event.srcElement : e.target; //目标对象,就是获取触发事件的对象
if (this.targetobj.className=="drag"){ //只有当这个对象的class为drag的时候才能拖动
this.dragapproved=1; //这是个标志为,表示开始移动了.
if (isNaN(parseInt(this.targetobj.style.left))){this.targetobj.style.left=0}; //如果目标对象的left和top值不是一个整数,则初始化为0
if (isNaN(parseInt(this.targetobj.style.top))){this.targetobj.style.top=0}; //同上
this.offsetx=parseInt(this.targetobj.style.left); //将目标对象的left和top值存起来, 回头计算坐标的时候用.
this.offsety=parseInt(this.targetobj.style.top); //同上
this.x=evtobj.clientX; //clientX获取鼠标指针向对于浏览器页面(或客户区)的水平坐标, 也存起来,后面moveit的计算中会使用
this.y=evtobj.clientY; //同上
if (evtobj.preventDefault)
evtobj.preventDefault(); //取消事件的默认动作
document.onmousemove=dragobject.moveit; //移动鼠标的时候,调用moveit方法,根据鼠标的位移,移动目标对象
}
},
moveit:function(e){
var evtobj=window.event? window.event : e
if (this.dragapproved==1){
this.targetobj.style.left=this.offsetx+evtobj.clientX-this.x+"px"; //这里是个计算,原先的left值(drag方法中存好的), 加上鼠标现在的x坐标,减去鼠标移动前的x坐标(这个也是drag方法中存好的),再加上"px"是单位, 并且赋值给目标对象, 这样对象就跟着鼠标动起来了.
this.targetobj.style.top=this.offsety+evtobj.clientY-this.y+"px"
return false
}
}
最后回到initialize方法中的document.onmouseup=function(){this.dragapproved=0},将dragapproved设为0,意思是移动结束了。。。