javascript - 随机方块(div)无法显示到页面上?

新手在学习js视频的时候,跟着敲的代码。实现的效果应该是在一个页面上随机生成小方块。
运行实际效果

图片描述

并没有方块出现

图片描述

但调试中已有方块产生!

代码如下:

<script >
/*
 * 产生随机数变量的
 */
(function (window) {
    function Random() {
    }
    Random.prototype.getRandom = function (min,max) {
        return Math.floor(Math.random()*(max-min)+min);
    };
    window.Random=new Random();//把局部对象暴露给window顶级对象,就成了全局对象
})(window);

/*
 * 产生小方块对象
 */
(function (window) {
    console.log(Random.getRandom(0,5))//这个是显示上面是否已经暴露成全局对象
    var map = document.querySelector(".map");//使用选择器的方式来获取元素,也可以使用.getElementById
    //小方块(食品)的构造函数
    function Food(width,height,color) {
        this.width=width||20;//默认的小方块的高
        this.height=height||20;
        this.x=0;//随机产生横坐标
        this.y=0;//随机产生纵坐标
        this.color=color;
        this.element=document.createElement("div");//生成一个装小方块的元素
    }
    //初始化小方块的显示效果与位置
     Food.prototype.init = function(map){
        var div = this.element;//设置小方块样式
        div.style.position = "absolute";//脱离文档流;
        div.style.width = this.width + "px";
        div.style.height = this.height + "px";
        div.style.backgroudcolor = this.color;
        map.appendChild(div);//把小方块加到地图中
        this.render(map);
    };
    //产生随机位置
     Food.prototype.render=function(map){
        var x =Random.getRandom(0,map.offsetWidth/this.width)*this.width;//随机生成横坐标
        var y =Random.getRandom(0,map.offsetHeight/this.height)*this.height;
        this.x=x;
        this.y=y;
        var div = this.element;
        div.style.left = this.x + "px";
        div.style.top = this.y + "px";
    };
    
     var fd = new Food(20,20,"green");
     fd.init(map);
     console.log(fd.x+"--"+fd.y);
     
})(window);
阅读 2.1k
1 个回答

背景色设置失败了

style.backgroundColor

图片描述

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题