</body>
<script>
// 面向对象方式 window.onload=function(){ class Drag{ constructor(obj){
this.obj=obj.elem;
this.minx=obj.rect===undefined?false:obj.rect.minx;
this.maxx=obj.rect===undefined?false:obj.rect.maxx;
this.miny=obj.rect===undefined?false:obj.rect.miny
this.maxy=obj.rect===undefined?false:obj.rect.maxy;
this.x=obj.dir.x===false? obj.dir.x:true;
this.y=obj.dir.y===false? obj.dir.y:true;
// 开始拖拽 this.down(); } down(){ var that=this; this.obj.onmousedown=function(e){ // alert(1) // console.log(this) var pw=this.offsetLeft; //距离事件源左上角距离 var ph=this.offsetTop; var aa=e.clientX; //浏览器距离 var bb=e.clientY; that.lx=aa-pw; that.ly=bb-ph;
that.move(this);
that.up();
}
}
move(obja){
var that=this;
document.onmousemove=function(e){
var aa=e.clientX;
var bb=e.clientY;
var left=aa-that.lx;
var top=bb-that.ly;
that.kw=obja.offsetWidth; //获取元素尺寸
that.kh=obja.offsetHeight;
if(left<that.minx){
left=that.minx
}
if(left>that.maxx-that.kw){
left=that.maxx-that.kw
}
if(top<that.miny){
top=that.miny
}
if(top>that.maxy-that.kh){
top=that.maxy-that.kh
}
if(that.x){
obja.style.left=left+"px";
}
if(that.y){
obja.style.top=top+"px";
}
}
}
up(){
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
}
}
}
var son=document.getElementsByClassName("son")[0];
new Drag({
elem:son,
rect:{minx:0,miny:0,maxx:400,maxy:400},
dir:{x:true,y:true}
})
}
</script>