天天看點

一個可以拖拽的DIV

<!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.;
		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.;
		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.οnmοusemοve=Drag.draging;
		document.οnmοuseup=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的坐标也加上去了, 這樣就感覺到是目前位置的移動。

繼續閱讀