实现鼠标拖动层的一种方法
调用方法
Endrag.bind('MoveDiv').bind('Div1').offSet({x:0,y:0});
通过多次调用bind方法可以绑定任意多个Div标签;
offSet设置偏移,默认x偏移和y偏移都为0,供调整使用
本方法不能通过子元素绑定操作父元素
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> 鼠标拖动层(可任意绑定DIV标签)(二) </title>
<script language="javascript" type="text/javascript">
/*
鼠标拖动层(可任意绑定DIV标签)(一)
作者:Anlige
联系方式:1034555083/zhanghuiguoanlige@126.com
调用方法:Endrag.bind('MoveDiv').bind('Div1').offSet({x:0,y:0});
参数说明:bind的参数为Div标签的ID属性或者Div对象本身;offSet的参数为偏移量,默认(不调用本方法)x,y偏移都为0
说明:通过多次调用bind方法绑定多个对象的拖动
*/
Endrag={
x0:0,y0:0,x1:0,y1:0,moveable:false,index:100,NS:(navigator.appName=='Netscape'),offSets:{x:0,y:0},
//开始拖动;
startDrag:function (e){
e = e ? e : (window.event ? window.event : null);
Endrag.getFocus(this);
if(e.button==(Endrag.NS)?0 :1) {
if(!Endrag.NS){this.setCapture()}
Endrag.x0 = e.clientX ;
Endrag.y0 = e.clientY ;
Endrag.x1 = parseInt(Endrag.abs(this).x);
Endrag.y1 = parseInt(Endrag.abs(this).y);
Endrag.moveable = true;
}
},
//拖动;
drag:function (e){
e = e ? e : (window.event ? window.event : null);
if(Endrag.moveable){
this.style.left = (Endrag.x1 + e.clientX - Endrag.x0 - Endrag.offSets.x) + "px";
this.style.top = (Endrag.y1 + e.clientY - Endrag.y0 - Endrag.offSets.y) + "px";
}
},
//停止拖动;
stopDrag:function (e){
if(Endrag.moveable) {
if(!Endrag.NS){this.releaseCapture();}
Endrag.moveable = false;
}
},
//获得焦点;
getFocus:function (obj){
if(obj.style.zIndex!=this.index){
this.index += 2;
var idx = this.index;
obj.style.zIndex=idx;
}
},
abs:function (element) {
var result = { x: element.offsetLeft, y: element.offsetTop};
element = element.offsetParent;
while (element) {
result.x += element.offsetLeft;
result.y += element.offsetTop;
element = element.offsetParent;
}
return result;
},
offSet:function(setting){
this.offSets=setting;
},
bind:function(obj){
obj=typeof(obj)=="object" ? obj:document.getElementById(obj);
obj.οnmοusedοwn=Endrag.startDrag;
obj.οnmοuseup=Endrag.stopDrag;
obj.οnmοusemοve=Endrag.drag;
return this;
}
};
</script>
</head>
<body οnlοad="Endrag.bind('MoveDiv').bind('Div1').offSet({x:0,y:0});">
<div id="MoveDiv" style="background:#ffffff;position:absolute;left:200px;top:50px;width:500px;height:200px;border:1px #dddddd solid;">
<div id="hand" style="line-height:25px;text-align:center;background:#f00">
拖动层
</div>
调用方法<br />
Endrag.bind('MoveDiv').bind('Div1').offSet({x:0,y:0});<br />
可以绑定任意多个Div标签;<br />offSet设置偏移,默认x偏移和y偏移都为0,供调整使用<br />
本方法不能通过子元素绑定操作父元素
</div>
<div id="Div1" style="background:#ffffff;position:absolute;left:400px;top:300px;width:300px;height:200px;border:1px #dddddd solid;">
<div id="Div2" style="line-height:25px;text-align:center;background:#f00">
拖动层
</div>
</div>
</body>
</html>