<!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></title>
</head>
<body>
<div style="background: #99CCFF; height: 140px; width: 180px; border: 1px solid #206100"
        class="dragdiv">
</div>
<div style="background: #99CCFF; height: 140px; width: 180px; border: 1px solid #206100"
        class="dragdiv">
</div>
</body>
</html>
<script type="text/javascript">
var Drag={

    dragged:false,
	ao:null,
	
    dragStart:function()
    {
        Drag.ao=event.srcElement;
        Drag.dragged=true;
        Drag.ao.style.position="absolute";
        Drag.ao.style.filter="alpha(opacity=70)";
        Drag.ao.style.cursor="move";
        Drag.ao.style.border="1px dashed red";
		Drag.lastX=event.clientX;               //自定义属性
		Drag.lastY=event.clientY;
		Drag.lastLeft=Drag.ao.offsetLeft;
		Drag.lastTop=Drag.ao.offsetTop;
    },
    draging:function(){//判断MOUSE的位置
		if(!Drag.dragged||Drag.ao==null)return;
		var tX=event.clientX;
		var tY=event.clientY;
		Drag.ao.style.left=parseInt(Drag.lastLeft)+tX-Drag.lastX;
		Drag.ao.style.top=parseInt(Drag.lastTop)+tY-Drag.lastY;
		},
    dragEnd:function(){
		if(!Drag.dragged)
			return;
		Drag.dragged=false;
		Drag.ao.style.border="1px solid #206100";
		Drag.ao.style.filter="";
	},
    
    init:function()
    {
        var dragdiv=document.getElementsByTagName('div');
        for(var i=0;i<dragdiv.length;i++)
        {
            if(dragdiv[i].className=="dragdiv")
            {
                dragdiv[i].attachEvent("onmousedown",Drag.dragStart);
            }
        }
        document.onmousemove=Drag.draging;
		document.onmouseup=Drag.dragEnd;
    }
};

Drag.init();
</script>

 

 拖拽其实并不是很难的东西,可是这个我也是弄了半天才弄出来的,其中的主要原因就是坐标的问题,关于offsetTop clientX ,都是比较棘手的

 

 

Drag.ao.style.left=parseInt(Drag.lastLeft)+tX-Drag.lastX;
Drag.ao.style.top=parseInt(Drag.lastTop)+tY-Drag.lastY;

这里我理解了好长的时间,如果没有加上parseInt(Drag.lastLeft),则当移动的时候div初始是定位在document.body的坐上角的,然后进行拖拽,div才能按正常的轨道滑行,而加上parseInt(Drag.lastLeft)了,在div移动初始的时候会把相对于document.body的坐标也加上去了, 这样就感觉到是当前位置的移动。

 

 

 

 

 

 

 

 

评论
fastwind 2008-07-24
恩 对 当时忘了FF了。。。 等我改一下吧
hejin1026 2008-07-24
经检测,在FF中N多的问题,改进了在帖出来吧
发表评论

您还没有登录,请登录后发表评论

fastwind
搜索本博客
我的相册
5d1599e6-b2ce-37a1-a9bc-bd3278699142-thumb
0be92b64-8320-3c0c-9365-4b33d8931699.jpg
共 2 张
最近加入圈子
存档
最新评论