<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> *{margin: 0;padding:0;} .one{width: 800px;height: 400px;border: 1px solid gray;margin: 0 auto;position: relative;} .one>div{border-radius: 50%;position: absolute;} </style> <script src="js/jquery-1.7.1.min.js"></script> <script type="text/javascript" src="js/jquery.easing.min.js"></script> </head> <body> <div class="one"></div> <script type="text/javascript"> $(function(){ //创建一个随机函数 function randFn(min,max){ return parseInt(Math.random()*(max-min)+min); } //创建小球的属性 function Ball(){ this.r=randFn(1,20); this.x=randFn(0,$(".one").width()-this.r*2); this.y=randFn(0,$(".one").height()-this.r*2); this.c="rgba("+randFn(0,255)+","+randFn(0,255)+","+randFn(0,255)+","+"0.5)"; this.speedX=randFn(-10,10); this.speedY=randFn(-6,6); this.div=$("<div></div>"); } //画小球 Ball.prototype.draw=function(){ this.div.css({ width:this.r*2, height:this.r*2, background:this.c, left:this.x, top:this.y }) $(".one").append(this.div); } Ball.prototype.run=function (){ if(this.speedX==0){ this.speedX=-4 } if(this.speedY==0){ this.speedY=-6 } if(this.x<0||this.x>800-this.r*2){ this.speedX *=-1 } if(this.y<0||this.y>400-this.r*2){ this.speedY *=-1 } this.x+=this.speedX; this.y+=this.speedY; this.div.css({ left:this.x, top:this.y }) } //创建一个数组 var ballArr=[]; for (var i = 0; i < 200; i++) { var ball=new Ball(); ballArr.push(ball); ball.draw(); }; //定时器 setInterval(function(){ for (var i = 0; i < ballArr.length; i++) { ballArr[i].run(); }; },100) }) </script> </body> </html>
转载于:https://www.cnblogs.com/ldlx-mars/p/6930392.html