<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>title</title> <style> .map { width: 800px; height: 600px; background-color: #CCC; position: relative; } </style> </head> <body> <div class="map"></div> <script src="common.js"></script> <script> //Generating random number objects (function (window) { function Random() { } Random.prototype.getRandom = function (min, max) { return Math.floor(Math.random() * (max - min) + min); }; //Exposing local objects to window top-level objects becomes the global object. window.Random = new Random(); })(window);//The way to call the constructor is to add the semicolon. //Creating small cube objects (function (window) { //console.log(Random.getRandom(0,5)); //Select the way to get the element object. var map = document.querySelector(".map"); //Function of food function Food(width, height, color) { this.width = width || 20;//Default width of small squares this.height = height || 20;//The default size of the block is high. //Abscissa and ordinate this.x = 0;//Randomly generated by abscissa this.y = 0;//Randomly generated ordinates this.color = color;//Background color of small squares this.element = document.createElement("div");//Elements of small squares } //Initialize the effect and location of the display of the small box -- display the map. Food.prototype.init = function (map) { //Set the style of small squares var div = this.element; div.style.position = "absolute";//Out of document flow div.style.width = this.width + "px"; div.style.height = this.height + "px"; div.style.backgroundColor = this.color; //Add small squares to map map. map.appendChild(div); this.render(map); }; //Generating random locations Food.prototype.render = function (map) { //Randomly generated horizontal and vertical coordinates 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"; }; //Instantiated object var fd = new Food(20, 20, "green"); fd.init(map); console.log(fd.x + "====" + fd.y); })(window); </script> </body> </html>