JS實現拖拽小案例
阿新 • • 發佈:2017-11-28
res pan urb posit htm eight || move use
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>簡單的拖拽</title> <link rel="stylesheet" href="../toolkit/reset.min.css"> <style> #box{ height: 200px; width: 200px; background-color: #e277ff; position: absolute; cursor: move; } </style> </head> <body> <div id="box"></div> <script> var box=document.getElementById("box"); function drag(e) { e=e||window.event; var _this=this; var mouseX=e.clientX, mouseY=e.clientY, boxL=this.offsetLeft, boxT=this.offsetTop; document.onmousemove=function (e) { e=e||window.event; var curMouseX=e.clientX, curMouseY=e.clientY, curBoxL=curMouseX-mouseX+boxL, curBoxT=curMouseY-mouseY+boxT; var minW=0,maxW=((document.documentElement.clientWidth||document.body.clientWidth)-_this.offsetWidth); var minH=0,maxH=((document.documentElement.clientHeight||document.body.clientHeight)-_this.offsetHeight); if(curBoxL<=minW){ curBoxL=minW; }else if(curBoxL>=maxW){ curBoxL=maxW } if(curBoxT<=minH){ curBoxT=minH; }else if(curBoxT>=maxH){ curBoxT=maxH; } _this.style.left=curBoxL+"px"; _this.style.top=curBoxT+"px"; }; document.onmouseup=function () { document.onmousemove=null; } } box.onmousedown=drag; </script> </body> </html>
JS實現拖拽小案例