js多个小球的运动
<!DOCTYPE html> <html> <head> <style type="text/css"> *{ margin: 0;padding: 0; } .box{ position: absolute; width: 50px; height: 50px; border-radius: 50%; } </style> </head> <body> <script type="text/javascript"> init(10); function init(num) { window.requestAnimationFrame = window.requestAnimationFrame||function (fn) { return setTime(fn,1000/60); };//兼容代码 for (var i = 0; i<num;i++) { var oDiv = document.createElement("div"); oDiv.className = "box"; oDiv.tSpeed = 1+i;//小球的横向速度 oDiv.lSpeed = 5+i;//小球的纵向速度 oDiv.style.background = Color(); document.body.appendChild(oDiv); } var OBox = document.querySelectorAll(".box"); var winHeight = document.documentElement.clientHeight - OBox[0].clientHeight; var winWidth = document.documentElement.clientWidth - OBox[0].clientWidth; window.onresize = function (){ winHeight = document.documentElement.clientHeight - OBox[0].clientHeight; winWidth = document.documentElement.clientWidth - OBox[0].clientWidth; }; move(); function move () { for (var i = 0; i<num;i++) { var oBox = OBox[i];//把每一个产生的box赋值给oBox var Left = oBox.offsetLeft; var Top = oBox.offsetTop; var moveLeft = Left + oBox.lSpeed; var moveTop = Top + oBox.tSpeed; if(moveLeft>=winWidth || moveLeft<=0){ moveLeft = Math.min(moveLeft,winWidth); moveLeft = Math.max(moveLeft,0); oBox.lSpeed= -oBox.lSpeed; oBox.style.background = Color(); }; if(moveTop>=winHeight || moveTop<=0){ moveTop = Math.min(moveTop,winHeight); moveTop = Math.max(moveTop,0); oBox.tSpeed = -oBox.tSpeed; oBox.style.background = Color(); } oBox.style.left = moveLeft + "px"; oBox.style.top = moveTop + "px"; }; requestAnimationFrame(move); }; //随机颜色 二种写法 /*var arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "A", "B","C","D"]; function Color(){ var str = "#"; for(var i=0;i<6;i++){ str += arr[Math.floor(Math.random()*arr.length)] } return str; }*/ //第二种写法 function Color() { var r = Math.floor(Math.random()*256), g = Math.floor(Math.random()*256), b = Math.floor(Math.random()*256); return "rgb("+r+","+g+","+b+")"; } } </script> </body> </html>