<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> div{ 10px; height: 10px; background: red; position: absolute; } </style> <script> function getPos(ev){ var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft; var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; return {x:ev.clientX +scrollLeft , y:ev.clientY + scrollTop}; } window.onload = function(){ //第一种方法: // document.onmousemove = function(ev){ // var oEvent = ev || event; // var aDiv = document.getElementsByTagName("div"); // // for(var i= aDiv.length-1;i>0;i--) // { // //后一个div跟着前一个div // aDiv[i].style.left = aDiv[i-1].offsetLeft +"px"; // aDiv[i].style.top = aDiv[i-1].offsetTop +"px"; // } // var pos = getPos(oEvent); //// alert(pos.x); // //第一个是跟着鼠标走 // aDiv[0].style.left = pos.x +"px"; // aDiv[0].style.top = pos.y +"px"; // } //第二种方法 document.onmousemove = function(ev){ clearInterval(time) var aDiv = document.getElementsByTagName("div"); var oEvent = ev || event; var pos = getPos(oEvent); var time ; var i = 0; function move(){ //定时器调用一次就给后一个div定位 aDiv[i].style.left =pos.x +"px"; aDiv[i].style.top = pos.y +"px"; i++; if(i>aDiv.length) { clearInterval(time); } } time = setInterval(move,10); } } </script> </head> <body style="height: 2000px;"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </body> </html>