js简单拖动

<script>
var x,y,z,down=false,obj   
function init(){
obj=event.srcElement     //事件触发对象
obj.setCapture()            //设置属于当前对象的鼠标捕捉
z=obj.style.zIndex          //获取对象的z轴坐标值
//设置对象的z轴坐标值为100,确保当前层显示在最前面
obj.style.zIndex=100
x=event.offsetX   //获取鼠标指针位置相对于触发事件的对象的X坐标
y=event.offsetY   //获取鼠标指针位置相对于触发事件的对象的Y坐标
down=true         //布尔值,判断鼠标是否已按下,true为按下,false为未按下
}

function moveit(){
//判断鼠标已被按下且onmouseover和onmousedown事件发生在同一对象上
 if(down&&event.srcElement==obj){
   with(obj.style){
/*设置对象的X坐标值为文档在X轴方向上的滚动距离加上当前鼠标指针相当于文档对象的X坐标值减鼠标按下时指针位置相对于触发事件的对象的X坐标*/

        posLeft=document.body.scrollLeft+event.x-x
/*设置对象的Y坐标值为文档在Y轴方向上的滚动距离加上当前鼠标指针相当于文档对象的Y坐标值减鼠标按下时指针位置相对于触发事件的对象的Y坐标*/
        posTop=document.body.scrollTop+event.y-y
   }
 }
}

function stopdrag(){
//onmouseup事件触发时说明鼠标已经松开,所以设置down变量值为false
down=false
obj.style.zIndex=z       //还原对象的Z轴坐标值
obj.releaseCapture() //释放当前对象的鼠标捕捉
}
</script>

<div onmousedown=init() onmousemove=moveit() onmouseup=stopdrag() style="position:absolute;left:20;top:190;width:100;height:150;border:1px solid #000000;z-index:1;background:#eeeeee">Layer 1</div>
<div onmousedown=init() onmousemove=moveit() onmouseup=stopdrag() style="position:absolute;left:60;top:10;width:100;height:150;border:1px solid #000000;z-index:2;background:#eeeeee">Layer 2</div>
<div onmousedown=init() onmousemove=moveit() onmouseup=stopdrag() style="position:absolute;left:100;top:90;width:100;height:150;border:1px solid #000000;z-index:3;background:#eeeeee">Layer 3</div>
posted @ 2009-07-30 15:01  XGU_Winner  阅读(117)  评论(0编辑  收藏  举报