<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
p{
width: 10px;
height: 10px;
border-radius: 50%;
position: absolute;
top:0;
left: 0;
}
</style>
<script>
window.οnlοad=function () {
var balls=[];
function creatBalls() {
for(var i=0;i<60;i++){
var ball=document.createElement('p');
ball.style.backgroundColor=randomColor();
document.body.appendChild(ball);
balls.push(ball);
}
}
creatBalls();
function randomColor() {
return 'rgb('+randomNum(0,255)+','+ randomNum(0,255)+','+randomNum(0,255)+')';
}
function randomNum(n,m) {
return Math.floor(Math.random()*(m-n+1)+n);
}
document.οnmοusemοve=function (e) {
var oEvent=e||window.event;
for(var i=balls.length-1;i>0;i--){
balls[i].style.top=balls[i-1].style.top;
balls[i].style.left=balls[i-1].style.left;
}
balls[0].style.left=oEvent.clientX+'px';
balls[0].style.top=oEvent.clientY+'px';
}
}
</script>
</head>
<body>
</body>
</html>
在实践中遇到的问题:
1.数组中的小球坐标应从数组尾开始,复制前一个小球的坐标;
for(var i=balls.length-1;i>0;i--)
2.从后将小球坐标改变完成后,再将第一个小球的坐标更新;
3.添加样式时忘记加.style;