定义一个对象,new 出来的每一个实例会生成一个彩色气泡,颜色、大小、位置、运动方向都随机设置

 <style>
    #box {
      margin: 100px auto;
      width: 600px;
      height: 600px;
      position: relative;
      overflow: hidden;
    }
  </style>
<body>
  <div id="box"></div>
</body>
 <script>
    /* 每个球都是一个对象 */
    /* 每个对象有 尺寸、背景色、位置(绝对定位,left top) */
    function Ball(size, left, top) {
      this.size = size || [10, 50];
      this.left = left || [0, 550];
      this.top = top || [0, 550];
    }
    // 根据球的尺寸生成具体的 html 结构
    Ball.prototype.createBall = function () {
      var _size = this.getRand(this.size[0], this.size[1]),
        _left = this.getRand(this.left[0], this.left[1]),
        _top = this.getRand(this.top[0], this.top[1]),
        _bgcolor = this.getBgColor();
      var _html = '<div style="width: ' + _size + 'px; height: ' + _size + 'px; border-radius: ' + _size + 'px; position: absolute; left: ' + _left + 'px; top: ' + _top + 'px; background: ' + _bgcolor + ';"></div>';
      return _html;
    }
    // 实现数值的随机 (min max为下标)
    Ball.prototype.getRand = function (min, max) {
      return Math.floor(Math.random() * (max - min + 1) + min);
    }
    // 返回随机的颜色值
    Ball.prototype.getBgColor = function () {
      var bgcolors = ["#f83600", "#FFF94C", "#0072ff", "#780206", "#7B920A", "#dc2430", "#A83279", "#00bf8f", "#FF512F", "#485563", "#061700", "#02AAB0"];
      return bgcolors[this.getRand(0, bgcolors.length - 1)];
    }

    var ball_html = '';
    for (let i = 1; i <= 100; i++) {
      ball_html += new Ball().createBall();
    }
    document.getElementById('box').innerHTML = ball_html;
  </script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值