0
点赞
收藏
分享

微信扫一扫

用js编写DOM案例,生成一个彩色气泡,颜色、大小、位置、运动方向都随机的动态效果。

犹大之窗 2022-04-29 阅读 179
javascriptjs

CSS页面代码:

<style>
    *{
      margin: 0;
      padding: 0;
    }
    #box{
      margin: 100px auto;
      width: 700px;
      height: 500px;
      position: relative;
      overflow: hidden;
    }
  </style>

HTML页面代码:

<div id="box"></div>

JS页面代码:

 <script>
   function Ball(size,left,top){
     this.size=size||[10,50];
     this.left=left||[0,650];
     this.top=top||[0,450];
   }
   Ball.prototype.createBall=function(){
     var _size=this.getRandom(this.size[0],this.size[1]),
     _left=this.getRandom(this.left[0],this.left[1]),
     _top=this.getRandom(this.top[0],this.top[1]),
     _bgcolor=this.getBgColor();
   var _div=document.createElement('div');
   _div.style.width =_size+'px';
   _div.style.height=_size+'px';
   _div.style.borderRadius=_size+'px';
   _div.style.backgroundColor=_bgcolor;
   _div.style.position='absolute';
   _div.style.left=_left+'px';
   _div.style.top=_top+'px';
   document.getElementById('box').appendChild(_div);
   var _direction=this.getRandom(1,4);
   switch(_direction){
     case 1:
       this.moveToleft(_div,_left,'left');
       break;
       case 2:
         this.moveToleft(_div,_left,'right');
         break;
         case 3:
           this.moveToTop(_div,_top,'top');
           break;
           case 4:
             this.moveToTop(_div,_top,'bottom');
             break;
             default:
               this.moveToleft(_div,_left,'left');
               break;
     }
  }
   Ball.prototype.moveToleft=function(element,left,direction){
     var x=left, _direction=direction;
     setInterval(function(){
       if(_direction=='right'){
         x++;
         if(x>=650){
           _direction='left';
         }
       }else{
         x--;
         if(x<=0){
           _direction='right';
         }
       }
       element.style.left=x+'px';
     },1000/60);
   }
   Ball.prototype.moveToTop=function(element,top,direction){
     var y=top, _direction=direction;
     setInterval(function(){
       if(_direction=='bottom'){
         y++;
         if(y>=450){
           _direction='top';
         }
       }else{
         y--;
         if(y<=0){
           _direction='bottom';
         }
       }
       element.style.top=y+'px';
     },1000/60);
   }
  //  返回颜色随机值
  Ball.prototype.getBgColor=function(){
    var bgcolors=["#f83600", "#FFF94C", "#0072ff", "#780206", "#7B920A", "#dc2430", "#A83279", "#00bf8f", "#FF512F", "#485563", "#061700", "#02AAB0"];
    return bgcolors[this.getRandom(0,bgcolors.length-1)];
  }
  // 实现颜色随机值
  Ball.prototype.getRandom=function(min,max){
    return Math.floor(Math.random()*(max-min+1)+min);
  }
  for(let i=1;i<=100;i++){
    new Ball().createBall();
  }
 </script> 

运行结果如下:

 运行效果为动态页面,因截图展示不出来动态,如有需要请自行运行参看效果。

举报

相关推荐

0 条评论