javascript實現拖動效果

實現一個<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" >
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 
<head> 
<style>
    #test{
    	width: 200px;
    	height: 200px;
    	background:#00B034;
    	position:absolute;
    	cursor:move;
    }
</style>
<title>測試頁面</title>
</head> 
<body>
	<div id="test"></div>
 <script type="text/javascript">
 		var pull=null;
 		var diffX=null;
 		var diffY=null;
 		var test=document.getElementById("test");
 		test.addEventListener("mousedown",function(event){
 			pull=event.target;
 			diffX=event.clientX-pull.offsetLeft;
 			diffY=event.clientY-pull.offsetTop;
 		},false);
 		test.addEventListener("mousemove",function(event){
 			if(pull!=null){
 		 		pull.style.left=(event.clientX-diffX)+"px";
 		 		pull.style.top=(event.clientY-diffY)+"px";
 		 	    pull.style.cursor="move";
 			}
 		},false);
        
 		test.addEventListener("mouseup",function(event){
 			pull=null;
 		},false);
 		test.addEventListener("mouseup",function(event){
 			pull=null;
 		},false);
 		test.addEventListener("mouseout",function(event){
 			pull=null;
 			 
 		},false);
 </script>
 
     </body>
    </html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章