JS面向对象编程实现的拖拽功能案例详解
本文实例讲述了JS面向对象编程实现的拖拽功能。分享给大家供大家参考,具体如下:
原始的面向过程代码:
拖拽
下面是面向对象的代码
drag.js
/**
*拖拽
*@param{Object}iddiv的id
*/
functionDrag(id){
this.oBox=document.getElementById(id);
this.disX=0;
this.disY=0;
var_this=this;
this.oBox.onmousedown=function(){
_this.fnDown();
}
}
//鼠标按下
Drag.prototype.fnDown=function(ev){
varoEvent=ev||event;
this.disX=oEvent.clientX-this.oBox.offsetLeft;
this.disY=oEvent.clientY-this.oBox.offsetTop;
var_this=this;
document.onmousemove=function(){
_this.fnMove();
};
document.onmouseup=function(){
_this.fnUp();
};
}
//鼠标移动
Drag.prototype.fnMove=function(ev){
varoEvent=ev||event;
this.oBox.style.left=oEvent.clientX-this.disX+'px';
this.oBox.style.top=oEvent.clientY-this.disY+'px';
}
//鼠标抬起
Drag.prototype.fnUp=function(){
document.onmousemove=null;
document.onmouseup=null;
}
drag.html
拖拽