上一篇文章实现了div鼠标进行拖拽,这次用面向对象的思想进行重写,面向对象的好处就是以后修改功能可以直接进行继承,只需修改自己关心的部分就可.
有关js面向对象,可以参考js 实现面向对象
没什么好说的了,直接放代码吧,没什么难度
/*
实现div随鼠标移动实现拖拽效果
div需指定宽高, position:absolute;
参数:
id: div的id
示例:
new Drag('div1');
*/
function Drag(id){
var _this=this;
this.disX=0;
this.disY=0;
this.oDiv=document.getElementById(id);
// 鼠标在div中按下,调使用方法
this.oDiv.onmousedown=function (){
_this.fnDown();
};
}
// 鼠标按下时调使用的方法
Drag.prototype.fnDown=function (ev){
var _this=this;
var oEvent=ev||event;
// 保存鼠标在div的位置
this.disX=oEvent.clientX-this.oDiv.offsetLeft;
this.disY=oEvent.clientY-this.oDiv.offsetTop;
document.onmousemove=function (){
_this.fnMove();
};
document.onmouseup=function (){
_this.fnUp();
};
// 阻止默认事件,防止移动过程中会选中内容
oEvent.preventDefault();
};
// 鼠标移动时调使用的方法
Drag.prototype.fnMove=function (ev){
var oEvent=ev||event;
// 修改div的位置
this.oDiv.style.left=oEvent.clientX-this.disX+'px';
this.oDiv.style.top=oEvent.clientY-this.disY+'px';
};
// 鼠标松开时调使用的方法
Drag.prototype.fnUp=function (){
document.onmousemove=null;
document.onmouseup=null;
};