js拖拽面向对象

//关于 this问题指向,函数里面还有函数的话,必须要把第一个函数的this保存下来给第二个函数访问。

<script>

window.onload=function(){
var t=new drag("box")
t.init();
}
function drag(name){
this.div=document.getElementById(name);
this.x;
this.y;
}
drag.prototype.init=function(){
var me=this;
this.div.onmousedown=function(e){
var e=e||event;
me.down(e);
}

}

drag.prototype.down=function(e){
this.x=e.clientX-this.div.offsetLeft;
this.y=e.clientY-this.div.offsetTop;
var me=this;
document.onmousemove=function(e){
var e=e||event;
me.move(e);

}


document.onmouseup=function(){
me.up()
}
}

drag.prototype.move=function(e){
this.divx=e.clientX-this.x;
this.divy=e.clientY-this.y;
this.width=document.documentElement.clientWidth-this.div.offsetWidth;
this.height=document.documentElement.clientHeight-this.div.offsetHeight;
if(this.divx<0){this.divx=0}else if(this.divx>this.width){this.divx=this.width}
if(this.divy<0){this.divy=0}else if(this.divy>this.height){this.divy=this.height}
this.div.style.left=this.divx+"px"
this.div.style.top=this.divy+"px"
var me=this;



}

drag.prototype.up=function(){
document.onmouseup=null;
document.onmousemove=null;
}


</script>
</head>


<body>
<div id="box" style=" width:100px;height:100px; background:#0F9; position:absolute"></div>




</body>

猜你喜欢

转载自blog.csdn.net/qq_36273128/article/details/52764038