JS随机产生小方块

创建的小方块,小方块要脱离标准文档流
第一步
创建随机数的对象,因为随机小方块改变的就是小方块的left和top值
第二步
创建小方块的对象

具体实现

<script>
    //1.产生随机数的对象
    (function () {
        function Random() {
        }
        Random.prototype.getRandom = function (min, max) {
            return Math.floor(Math.random() * (max - min) + min);
        }
        window.random = new Random();

    })();
   
    //2.产生小方块的对象
    (function () {
        var map = document.getElementById("map");
        //小方块的构造函数
        function Food(width,height, color, x, y) {
            this.width = width || 20;//设置默认的小方块的宽度
            this.height = height ||20;
            this.color = color || "pink";
            //需要随机产生的left和top值
            this.x = x || 0;
            this.y = y || 0;

            //创建一个div盒子-->即小方块
            this.element = document.createElement("div");
        }
        //初始化小方块显示的位置
        Food.prototype.init = function () {
            //1.设置小方块的样式
            console.log(this.element);
            var div = this.element;
            div.style.width = this.width + "px";
            div.style.height = this.height + "px";
            div.style.backgroundColor = this.color;
            div.style.position = "absolute";
            //2.把小方块添加到map中
            map.appendChild(div);
            //3.位置随机
            this.render();
        }
        //添加位置随机的方法
        Food.prototype.render = function () {
            // 0-40  --->随机区间0-39
            this.x = random.getRandom(0,map.offsetWidth/this.width )* this.width;
            this.y = random.getRandom(0,map.offsetHeight/this.height )* this.height;
            //设置小方块的left和top值
            this.element.style.left = this.x + "px";
            this.element.style.top = this.y + "px";
        }

        window.food = new Food();
        //food.init();

    })();

    food.init();
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值