首页 > Web开发 > 详细

JS简单拖拽效果

时间:2017-12-28 20:33:21      阅读:261      评论:0      收藏:0      [点我收藏+]

<!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

JS简单拖拽效果

原文:https://www.cnblogs.com/luludehuhuan/p/8137394.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!