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>
来源: http://www.qdfuns.com/article/19662/abe684ea44f280abd4543729a83eb49c.html