一个简单的拖拽功能
转载一夜成殇
拖拽写法太多了,自己没事也写个试试,普通写法不是很难,写个面向对象的拖拽。新加了点继承重写drag的方法。
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div1{
position:absolute;
width:200px;
height:200px;
background-color:red;
z-index:1;
}
#div2{
position:absolute;
width:200px;
height:200px;
background-color:yellow;
z-index:1;
}
</style>
<script>
window.onload=function(){
new Drag('div1');
new LimitDrag('div2')
}
var index=1;
function Drag(obj){
var _this=this;
this.obj=document.getElementById(obj);
this.disX=0;
this.disY=0;
this.obj.onmousedown=function(ev){
_this.fnDown(ev);
}
}
Drag.prototype.fnDown=function(ev){
var _this=this;
var event=ev||event;
this.obj.style.zIndex=++index;
this.disX=event.clientX-this.obj.offsetLeft;
this.disY=event.clientY-this.obj.offsetTop;
document.onmousemove=function(ev){
_this.fnMove(ev);
return false;
}
document.onmouseup=function(){
_this.fnUp();
}
}
Drag.prototype.fnMove=function(ev){
var event=ev||event;
var left=event.clientX-this.disX;
var top=event.clientY-this.disY;
this.obj.style.left=left+'px';
this.obj.style.top=top+'px';
}
Drag.prototype.fnUp=function(ev){
document.onmousedown=null;
document.onmousemove=null;
}
//继承drag的属性
function LimitDrag(obj){
Drag.call(this,obj);
}
//继承drag的方法
for(var i in Drag.prototype){
LimitDrag.prototype[i]=Drag.prototype[i];
}
//重写drag方法,增加范围限制
LimitDrag.prototype.fnMove=function(ev){
var event=ev||event;
var left=event.clientX-this.disX;
var top=event.clientY-this.disY;
var width=document.documentElement.clientWidth;
var height=document.documentElement.clientHeight;
if(left<0){
left=0;
}else if(left>(width-this.obj.offsetWidth)){
left=width-this.obj.offsetWidth;
}
if(top<0){
top=0;
}else if(top>(height-this.obj.offsetHeight)){
top=height-this.obj.offsetHeight;
}
this.obj.style.left=left+'px';
this.obj.style.top=top+'px';
}
</script>
</head>
<body >
<div id="div1">
1111
</div>
<div id="div2">2222</div>
</body>
</html>
如图