单例模式封装简单的拖拽。
//单例模式:一个类能返回一个对象的引用和一个获得该实例的方法。
var setDrag=(function(window,jQuery,undefined){
//创建构造函数,类默认规定首字母都是大写的
function Drag(){
this.obj=null;
this.dirX=0;
this.dirY=0;
}
Drag.prototype.init=function(ele,whenDown,whenUp){
var that=this;//避免this混淆,存储外面的this
this.obj=$(ele)[0];//jQuery选择器选择出来的只能用jQuery操作,用[0]将其变成可用JS方法的DOM
//当鼠标按下
this.obj.onmousedown=function(ev){
var ev=event||window.event
that.mousedownFun(ev);//通过that存储的this(此时this指向drag)调用原型上的方法
//当鼠标移动
document.onmousemove=function(){
that.mousemoveFun(ev);
};
//当鼠标抬起
document.onmouseup=function(){
that.mouseupFun()
};
//清除默认事件,防止文字选中
return false;
};
};
//当鼠标按下的时候用鼠标的位置减去元素到左侧的距离,就得出鼠标距离元素左侧的距离
Drag.prototype.mousedownFun=function(ev){
//兼容IE和标准下的事件对象
var ev=event||window.event
this.dirX=ev.clientX-this.obj.offsetLeft;
this.dirY=ev.clientY-this.obj.offsetTop;
};
//当鼠标移动结束后,用结束后的鼠标的位置减去鼠标在元素上的位置,就可以得出元素距离页面顶部和左侧的距离
Drag.prototype.mousemoveFun=function(ev){
var ev=event||window.event
//这里做了一个碰撞检测,让元素不出浏览器的范围
if(ev.clientX-this.dirX<0){
this.obj.style.left=0;
}else if(ev.clientX-this.dirX+this.obj.clientWidth>$(window).width()){
//this.obj.clientWidth得出的数字this.obj.style.width得出的数字+px
this.obj.style.left=$(window).width()-this.obj.clientWidth+"px"
//不要忘记结尾的+"px",不要忘记结尾的+"px",不要忘记结尾的+"px"
}else{
this.obj.style.left=ev.clientX-this.dirX +"px";
};
if(ev.clientY-this.dirY<0){
this.obj.style.top=0;
}else if(ev.clientY-this.dirY+this.obj.clientHeight>$(window).height()){
this.obj.style.top=$(window).height()-this.obj.clientHeight+"px"
}else{
this.obj.style.top=ev.clientY-this.dirY +"px";
}
};
//当鼠标抬起的时候清除doucument上的事件,释放内存
Drag.prototype.mouseupFun=function(){
document.onmousemove=null;
document.onmouseup=null;
};
返回构造函数,为了让外面的setDrag接收,形成单例模式
return Drag;
})(window,jQuery)
调用:
$(document).ready(function(){
var newDrag=new setDrag();
newDrag.init("p")
})
注:被拖拽的元素一定要设置position: absolute;负责拖拽不了。