鼠标拖拽跟随

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box{
width: 50px;
height: 50px;
background: red;
position: absolute;
top: 0;
left: 0;
cursor: pointer;
}
</style>
</head>
<body>
<div id="box">

</div>
<script type="text/javascript">
var box = document.getElementById("box")
box.onmousedown = function(ev){
ev = ev || event;
var x = ev.clientX - box.offsetLeft;
var y = ev.clientY - box.offsetTop;
document.onmousemove = function(ev){
ev = ev || event;
x1 = ev.clientX - x ;
y1 = ev.clientY - y ;
box.style.left = x1 +'px';
box.style.top = y1 + 'px';
}
}
box.onmouseup = function(){
document.onmousemove = null;
}

// document.addEventListener('mousedown',function(){
// document.addEventListener('mousemove',function(ev){
// ev = ev || event;
// box.style.left = ev.clientX +'px';
// box.style.top = ev.clientY + 'px';
// })
// })


</script>
</body>
</html>

posted @ 2017-03-07 09:55  张正-博客园  阅读(232)  评论(0编辑  收藏  举报