A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

酷ma萌

初级黑马

  • 黑马币:

  • 帖子:

  • 精华:

© 酷ma萌 初级黑马   /  2019-3-19 16:16  /  949 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

大神们,大佬们,我是一名管理专业的产品经理,利用碎片时间在学习代码。在技术上是小白中的小白,今天小弟,哦不,是上星期遇到一个问题---------贪吃蛇项目的问题,望大佬们帮忙看看,谢谢!代码和老师写的一模一样,但是报错解决不了。
首先,HTML部分
[HTML] 纯文本查看 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #map {
            width: 800px;
            height: 600px;
            background-color: #ccc;
            position: relative;
        }
    </style>
</head>
<body>
    <div id=" map "></div>
    <script src ="tools.js" ></script>
    <script src ="food.js" ></script>
    <script>
    var map = document.getElementById('div');
    var food = new Food();
    food.render();
    </script>
</body>
</html>


再是js的食物Food部分
[JavaScript] 纯文本查看 复制代码
// 关于食物对象代码
function Food(obj) {
    obj = obj || {};
    this.width = obj.width || 20;
    this.height = obj.height || 20;
    this.bgc = obj.bgc || 'green';
    this.x = obj.x || 0;
    this.y = obj.y || 0;
}

// 将食物渲染上页面的代码
Food.prototype.render = function () {
    var div = document.createElement('div');
    div.style.width = this.width + 'px';
    div.style.height = this.height + 'px';
    div.style.backgroundColor = this.bgc;
    /*
    * 由于在贪吃蛇的游戏中,Food只new一次,所以获取随机数的代码不卸载构造函数中,
    * 而是要卸载render中,为什么要卸载render中呢?
    * 是因为,如果蛇吃到了食物,我们还要调用render方法
    * */
    this.x = Tool.getRandom(0, map.offsetWidth - this.width);
    this.y = Tool.getRandom(0, map.offsetHeight - this.height);

    div.style.left = this.x + 'px';
    div.style.top = this.y + 'px';
    div.style.position = 'absolute';
    map.appendChild('div');
}



最后是工具部分
[JavaScript] 纯文本查看 复制代码
// 工具型函数
var Tool = {
    // 获取min~max的随机整数
    getRandom : function (min,max) {
        return Math.floor(Math.random()*(max - min + 1)) + min;
    }
}


在游览器中报错:
Uncaught TypeError: Cannot read property 'offsetWidth' of null
    at Food.render (food.js:22)
    at index.html?_ijt=50h0mm7rpvsq6b118vsh23u6q:22

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马