javascript关于拖拽div的问题
最近简单写了一个简单的关于拖拽div的js脚本如下:
<html>
<head>
<title> New Document </title>
<style type="text/css">
body{margin:0}
.drag{width:40px;height:40px;background:#123321;position:relative}
</style>
</head>
<body>
<div id="drag" class="drag" onmousedown="move(event)" onmousemove="upmove(event)" onmouseup="stopdrag(event)"></div>
<script type="text/javascript">
var x,y,cx,cy;
var down=false;
var time=0;
function move(event){
var even=event?event:window.event;
var drag=document.getElementById("drag");
x=drag.offsetLeft;
y=drag.offsetTop;
cx=even.clientX;
cy=even.clientY;
console.log("cx:"+cx);
console.log("cy:"+cy);
down=true;
}
var cx1,cy1;
function upmove(event){
var even=event?event:window.event;
var drag=document.getElementById("drag");
if(down){
if(time == 0){
cx1=even.clientX-cx;
cy1=even.clientY-cy;
}else{
cx1=even.clientX-10;
cy1=even.clientY-10;
}
console.log("even.clientX:"+even.clientX);
console.log("even.clientY:"+even.clientY);
console.log("cx1:"+cx1);
console.log("cy1:"+cy1);
drag.style.left=cx1+"px";
drag.style.top=cy1+"px";
time++;
}
}
function stopdrag(event){
var even=event?event:window.event;
var drag=document.getElementById("drag");
down=false;
drag.id="drag";
drag.style.left=cx1+"px";
drag.style.top=cy1+"px";
}
</script>
</body>
</html>