JS简单拖拽效果

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖拽</title>
<style>
*{margin:0;padding:0;}
#box{width:100px;height:100px;background-color: #f00;position:absolute;left:0;top:0;}
</style>
</head>
<body>
<div id="box">

</div>
<script>
var box=document.getElementById("box");
box.onmousedown=function(e){
//获取获取鼠标初始位置
var mouse_x=e.clientX;
var mouse_y=e.clientY;

var box_x=box.offsetLeft;
var box_y=box.offsetTop;
document.onmousemove=function(e){
var mouse_now_x=e.clientX;
var mouse_noe_y=e.clientY;
result_x=box_x+mouse_now_x-mouse_x;
result_y=box_y+mouse_noe_y-mouse_y;
if(result_x<0){
result_x=0;
}else if(result_x>document.body.clientWidth-100){
result_x=document.body.clientWidth-100
}
if(result_y<0){
result_y=0;
}
box.style.left=result_x+"px";
box.style.top=result_y+"px";
}
}
box.onmouseup=function(){
document.onmousemove=null;
}
</script>
</body>
</html>

 

WEB前端学习交流群21 598399936

posted @ 2017-12-28 19:19  噜噜修  阅读(144)  评论(0编辑  收藏  举报