拖拽库封装代码
//EventEmitter类:给实例对象的自定义行为绑定多个方法,订阅发布执行
function EventEmitter() {}
EventEmitter.prototype.on=function (type,fn) {
if(!this[type]){
this[type]=[];
}
var a=this[type];
if(a.length){
for(var i=0; i<a.length; i++){
if(a[i]===fn) return;
}
}
a.push(fn);
return this;//进行链式操作
};
EventEmitter.prototype.fire=function(type,e){
//保证fire函数执行时,里面的this为实例对象;
var a=this[type] || [];
if(a.length){
for(var i=0; i<a.length; i++){
if(typeof a[i]==="function"){
a[i].call(this,e);//保证函数执行时,里面的this为实例对象,并传事件对象实参;
}else{
a.splice(i,1);
i--;
}
}
}
};
EventEmitter.prototype.off=function (type,fn) {
var a=this[type];
if(a.length){
for(var i=0; i<a.length; i++){
if(a[i]===fn){
a[i]=null;
break;
}
}
}
};
//Drag类:拖拽
function Drag(opt) {
opt=opt||{};
if(!opt.ele) return;
this.ele=opt.ele;
this.disX=null;
this.disY=null;
this.DOWN=null;
this.MOVE=null;
this.UP=null;
this.init();
}
//原型链继承
Drag.prototype=new EventEmitter();
//原型链继承后,原型上没有自己类的constructor属性,需要重新设置
Drag.prototype.constructor=Drag;
//原型上公共方法
Drag.prototype.init=function () {
//绑定down事件;
this.DOWN=processThis(this.down,this);
on(this.ele,"mousedown",this.DOWN);
};
Drag.prototype.down=function (e) {
//获取鼠标相对于元素的位置disX,disY
this.disX=e.clientX-this.ele.offsetLeft;
this.disY=e.clientY-this.ele.offsetTop;
//绑定move,up事件
this.MOVE=processThis(this.move,this);
this.UP=processThis(this.up,this);
if(this.ele.setCapture){//IE浏览器
this.ele.setCapture();//焦点捕获
on(this.ele,"mousemove",this.MOVE);
on(this.ele,"mouseup",this.UP);
}else{//标准浏览器
//将事件绑定到document上,阻止默认事件发生;
on(document,"mousemove",this.MOVE);
on(document,"mouseup",this.UP);
e.preventDefault();
}
this.fire("myDragDown",e);//添加接口,实例对象调用fire公共方法,自定义行为是myDragDown
};
Drag.prototype.move=function (e) {
//获取新位置,无边界值判断
var l=e.clientX-this.disX;
var t=e.clientY-this.disY;
//设置新位置
this.ele.style.left=l+"px";
this.ele.style.top=t+"px";
this.fire("myDragMove",e);//添加接口,实例对象调用fire公共方法,自定义行为是myDragMove
};
Drag.prototype.up=function (e) {
if(this.ele.releaseCapture){
this.ele.releaseCapture();//释放焦点捕获;
off(this.ele,"mousemove",this.MOVE);
off(this.ele,"mouseup",this.UP);
}else{
off(document,"mousemove",this.MOVE);
off(document,"mouseup",this.UP);
}
this.fire("myDragUp",e);//添加接口,实例对象调用fire公共方法,自定义行为是myDragUp
};