實現一個<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>