---
title: "一个可以拖拽的DIV"
author: "fastwind"
date: "2008-07-22T00:05:47Z"
tags: []
slug: "div"
draft: false
lastmod: "2008-07-22T00:05:47Z"
id: 217395
url: "https://fastwind.iteye.com/blog/217395"
---

```
<!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的坐标也加上去了， 这样就感觉到是当前位置的移动。