原生js如何做一個鏈式運動,JavaScript怎麼做滑鼠跟隨效果
阿新 • • 發佈:2019-01-27
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> *{ margin:0; padding:0; list-style: none } div{ position:absolute; width:20px; height:20px; background-color:red; left:60px; top:0px; } </style> </head> <body style="height:1000px; width:1000px;"> <div > 0 </div> <div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div><div > 0 </div> </body> </html> <script type="text/javascript"> window.onload = function(){ document.body.onmousemove = function(event){ let evt = event || window.event; //改變除了第一方塊外的其它方塊 let unitDivs = document.getElementsByTagName("div"); for(let i=unitDivs.length-1;i>0;i--){ unitDivs[i].style.left = unitDivs[i-1].style.left; unitDivs[i].style.top = unitDivs[i-1].style.top; } //改變第一個方塊的位置 unitDivs[0].style.left = evt.pageX+"px"; unitDivs[0].style.top = evt.pageY+"px"; } } </script>