js实现随机小球。气泡

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

也就是随着页面的刷新会生成不同的小球。

结果演示:

随机彩球演示视频

css样式代码:

<style>
        * {
            margin: 0;
            padding: 0;
        }

        .container {
            margin: 200px auto;
        }

        .box {
            width: 500px;
            height: 500px;
            margin: 200px auto;
            position: relative;
            overflow: hidden;
        }

    </style>

html代码:

 <div class="container">
        <div class="box" id='box'>
            <!-- <div class="bubble"
                style="width:40px;height:40px;border-radius: 40px;background-color: aqua;position:absolute;left:40px;top:40px;">
            </div> -->

        </div>
    </div>

js的代码:

//利用math方法里面的random随机取值,公式:

Math.random*(n-m)+m 是取值m-n之间的值 m<= X < n  

Math.random*(n-m+1)+m;

里面如果再加1,就是不等式两边都是可以等的  m<= X < =n  

           

<script>
        /* 每个球都是一个对象 */
        /* 每个对象有 尺寸、背景色、位置(绝对定位,left top) */
        function CreatBubble(size, bgcolors, left, top) {
            this.size = size || [10, 50];//逻辑短路运算。或运算。         
            this.bgcolors = bgcolors || ["#f83600", "#FFF94C", "#0072ff", "#780206", "#7B920A", "#dc2430", "#A83279", "#00bf8f", "#FF512F", "#485563", "#061700", "#02AAB0"];
            this.left = left || [0, 450];//由于要做一个500*500的box里面的彩球,宽高定位要取少一点少的部分是尺寸大小,不然生成的小球右边和下边会不完整。
            this.top = top || [0, 450];
        }
        //根据小球生成html结构,尺寸等数值用随机数值。
        CreatBubble.prototype.outBubble = 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]);
            _bgcolors = this.bgcolors[this.getRand(0, this.bgcolors.length - 1)];//里面取到的随机值是下标,要放到颜色数组里面
           var _html = '<div class="bubble"style="width:'+ _size+'px;height:'+ _size+'px;border-radius: '+ _size+'px;background-color:'+ _bgcolors+';position:absolute;left:'+ _left+'px;top:'+ _top+'px;"></div >';
            return _html;
        }
        //实现数值的随机取值
        CreatBubble.prototype.getRand = function (min, max) {
            //利用math方法里面的random随机取值,公式:Math.random*(n-m)+m 是取值m-n之间的值 m<= X < n   里面如果再加1,就是不等式两边都是可以等的
            return Math.floor(Math.random()* (max - min + 1) + min);
        }
        // 生成一定数量气泡,并写入html中
        var ball_html = '';
        for (var i = 0; i <= 100; i++) {
            ball_html += new CreatBubble().outBubble();
        }
        document.getElementById('box').innerHTML = ball_html;


    </script>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值