CSS代码:
<style type="text/css">
#cube{
position:absolute ;
width: 100px;
height: 100px;
background-color: lightblue;
left:30px;
top:30px;
}
</style>
JS代码:
<script type="text/javascript">
!function(){
var cube=document.getElementById("cube");
var currentStyle=document.defaultView.getComputedStyle(cube);
var xDown,yDown,left,top,xMove,yMove;
function startMove(evt){
xDown=evt.clientX;
yDown=evt.clientY;
left=currentStyle.left;
top=currentStyle.top;
cube.addEventListener("mousemove",moving);
}
function moving(evt){
xMove=evt.clientX;
yMove=evt.clientY;
var xDistanse=xMove-xDown;
var yDistanse=yMove-yDown;
cube.style.top=(parseInt(top)+yDistanse)+"px";
cube.style.left=(parseInt(left)+xDistanse)+"px";
}
function stopMove(evt){
cube.removeEventListener("mousemove",moving);
cube.style.top=document.defaultView.getComputedStyle(cube).top;
cube.style.left=document.defaultView.getComputedStyle(cube).left;
}
cube.addEventListener("mousedown",startMove);
cube.addEventListener("mouseup",stopMove);
}();
</script>
网友评论