js多个小球的运动
2017-08-27 10:36
351 查看
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>
相关文章推荐
- Js实现简单的小球运动特效
- JS小球抛物线轨迹运动的两种实现方法详解
- js实现小球抛物线轨迹运动的两种方式
- Js实现简单的小球运动特效
- 模拟真实物体运动的js动画库插件-Anima
- 百度地图API——单点沿线运动(js)
- js实现带简单弹性运动的导航条
- 用js实现小球的自由移动代码
- JS完美运动框架
- JS - 匀速运动框架
- 轻质杆两端小球和质心运动动画
- js实现缓动效果-让div运动起来
- js运动练习
- 原生js如何做一个链式运动,JavaScript怎么做鼠标跟随效果
- js多个物体运动的问题1
- 完美运动(链式运动)JS框架
- js的弹性运动
- 自由运动的小球
- HTML5 做波形运动的小球
- JS-运动基础(一)