<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>tuozhuai</title> <style> *{ margin: 0px;padding: 0px; } div{ width: 100px; height: 100px; background: red; position: absolute; } #div1{ width: 100px; height: 100px; background: red; position: absolute; } </style> </head> <body> <div id="div1"></div> <div id="div2"></div> <div id="div3"></div> <div id="div4"></div> <script> function drag(id) { var odiv=document.getElementById(id) odiv.οnmοusedοwn=function (ev) { var ev=ev||event; var disX=ev.clientX-odiv.offsetLeft; var disY=ev.clientY-odiv.offsetTop; document.οnmοusemοve=function (ev2) { var ev2=ev2||event; var left=ev2.clientX-disX; var top=ev2.clientY-disY; var w = document.documentElement.clientWidth || document.body.clientWidth; var h = document.documentElement.clientHeight || document.body.clientHeight; if(left > w - odiv.offsetWidth){ left = w - odiv.offsetWidth } if(left< 0){ left = 0; } if(top< 0){ top = 0; } if(top > h - odiv.offsetHeight){ top = h - odiv.offsetHeight } odiv.style.left=left+"px"; odiv.style.top=top+"px" } document.οnmοuseup=function (ev2) { document.οnmοusemοve=null } } } drag("div1") drag("div2") drag("div3") drag("div4") </script> </body> </html>
js实现div拖拽
最新推荐文章于 2024-10-10 16:20:12 发布