Javascript实现对象的拖动操作

来源:互联网 发布:干支纪年算法 编辑:程序博客网 时间:2024/05/22 04:58
学着写的一段鼠标拖动的代码,感觉挺有意思。
本例需要掌握的技巧比较多,捕捉鼠标,获取鼠标位置(相当于对象),释放鼠标捕捉,文档的滚动距离。
1.       setCapture() 设置属于当前文档的对象的鼠标捕捉。
2.       event.offsetX 设置或获取鼠标指针位置相对于触发事件的对象的 x 坐标。
3.       event.offsetY 设置或获取鼠标指针位置相对于触发事件的对象的 y 坐标。
4.       releaseCapture() 释放当前文档中对象的鼠标捕捉。
5.       scrollLeft 设置或获取位于对象左边界和窗口中目前可见内容的最左端之间的距离。
6.       scrollTop 设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离。
7.       with 为一个或多个语句设定默认对象。
8.       event.x,event.y 设置或获取鼠标指针位置相对于窗口对象的 x ,y坐标。
<!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" xml:lang="en" lang="en">
<head>
  
<title></title>
  
<style type="text/css">
  #l1
{
    position
:absolute;top:100px;left:100px;
    width
:100px;height:150px;border:1px solid #ccc;
    background
:#f00;
    z-index
:1
    
}
  #l2
{
    position
: absolute;top:150px;left:150px;
    width
:100px;height:150px;border:1px solid #666;
    background
:#0f0;
    z-index
:2
  
}
  #l3
{
    position
: absolute;top:200px;left:200px;
    width
:100px;height:150px;border:1px solid #999;
    background
:#00f;
    z-index
:3;
  
}
  
</style>
  
<script type="text/javascript">
    
var x,y,z,down=false,obj;
    
function init(){
        obj
=event.srcElement;   //获取焦点对象
        obj.setCapture();           //设置鼠标捕捉
        z=obj.style.zIndex;         //取得原z轴位置
        obj.style.zIndex=100;       //设定在最上层
        x=event.offsetX;            //获取鼠标指针相对于触发事件的对象的x位置
        y=event.offsetY;            //获取鼠标指针相对于触发事件的对象的y位置
        down=true;                  //设置鼠标状态为按下状态
    }
    
function moveIt(){
        
if(down&&event.srcElement==obj){
            
with(obj.style){
                posLeft
=document.body.scrollLeft+event.x-x;
                posTop
=document.body.scrollTop+event.y-y;
            }
        }
    }
    
function stopDrag(){
        down
=false;
        obj.style.zIndex
=z;
        obj.releaseCapture();
    }
  
</script>
</head>
<body>
<div id="l1" onmousedown="init()" onmousemove="moveIt()" onmouseup="stopDrag()">level1</div>
<div id="l2" onmousedown="init()" onmousemove="moveIt()" onmouseup="stopDrag()">level2</div>
<div id="l3" onmousedown="init()" onmousemove="moveIt()" onmouseup="stopDrag()">level3</div>
</body>
</html>
原创粉丝点击