<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>拖拽事件回放</title> <style> *{ margin:0; padding:0; } #box{ width:100px; height:100px; background: #f00; position: absolute; left:0; top:0; } button{ float:right; } </style> </head> <body> <div id="box"></div> <button id="btn">回放</button> <script> var arrX=[],arrY=[]; box.οnmοusedοwn=function(e){ var ev =e||event; var l=ev.clientX-box.offsetLeft; var t=ev.clientY-box.offsetTop; document.οnmοusemοve=function(e){ var ev = e||event; var needLeft=ev.clientX-l; var needTop=ev.clientY-t; var maxLeft=innerWidth-box.offsetWidth; var maxTop=innerHeight-box.offsetHeight; //不超出顶部距离 needTop<0?needTop=0:needTop; //不超出左边距离 needLeft<0?needLeft=0:needLeft; //不超出底部距离 needTop>maxTop?needTop=maxTop:needTop; //不超出右边距离 needLeft>maxLeft?needLeft=maxLeft:needLeft; arrX.push(needLeft); arrY.push(needTop); box.style.left=needLeft+'px'; box.style.top=needTop+'px'; // console.log(arrX,arrY); }; document.οnmοuseup=function(){ document.οnmοusemοve=document.οnmοuseup=null; }; return false; }; var timer=null; btn.οnclick=function(){ clearInterval(timer); timer=setInterval(function(){ if(arrY.length==0){ clearInterval(timer); } box.style.left=arrX.pop()+'px'; box.style.top=arrY.pop()+'px'; },20); }; </script> </body> </html>
拖拽事件回放
最新推荐文章于 2022-08-22 08:46:56 发布