单例模式封装简单的拖拽
来源:互联网 发布:单片机51交通灯程序 编辑:程序博客网 时间:2024/05/19 13:16
//单例模式:一个类能返回一个对象的引用和一个获得该实例的方法。
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("div")
})
注:被拖拽的元素一定要设置position: absolute;负责拖拽不了。
- 单例模式封装简单的拖拽
- Okhttp的单例模式封装
- 封装好的单例模式
- 简单的单例模式
- 简单的单例模式
- 简单的单例模式
- 简单的设计模式-单例模式
- Okhttp3 简单单例封装
- Android两种典型的单例模式及SharedPrefenences单例模式的封装
- PHP封装的一个单例模式Mysql操作类
- 封装单例模式和拦截器的使用
- 简单单例模式
- 一个单例模式的简单例子
- 单例模式的简单代码实现
- 简单的单例模式类
- qt中简单的单例模式
- 一个简单的单例模式
- 一个简单的单例模式
- 数的读法
- c++ 与 构造函数
- SQLServer锁的概述
- 绘图级的动画
- poj1655 求树的重心
- 单例模式封装简单的拖拽
- Major GC和Full GC的区别以及触发条件
- JAVA设计模式--单例模式
- 微信企业号的消息发送
- 70.Failed to install Safe.apk on device 'emulator-5554': timeout问题解决方法
- Android数据库框架greenDao学习笔记(二)---注解
- 嵌入式面试题——ARM试题(一)
- tcpip基础一
- Java虚拟机学习