html代码: <div class="map"></div>
css代码:
<style> .map { width: 400px; height: 400px; background-color: skyblue; } </style>
js代码:
//产生随机数 (function () { function Random() { } Random.prototype.getRandom = function (min, max) { return parseInt(Math.random() * (max - min) + min); } window.random = new Random(); }()); (function () { var map = document.querySelector(".map"); //小方块 function Food(width, height, color) { this.width = width || 20; this.height = height || 20; this.color = color || "pink"; this.element = document.createElement("div");//创建小方块 //随机位置 this.x = 0; this.y = 0; } Food.prototype.init = function () { var dvObj = this.element; map.appendChild(dvObj); //小方块位置随机--脱离文档流 dvObj.style.position = "absolute"; dvObj.style.width = this.width + "px"; dvObj.style.height = this.height + "px"; dvObj.style.background = this.color; this.render(); } //随机位置 Food.prototype.render = function () { var dvObj = this.element; var x = random.getRandom(0, map.offsetWidth / this.width); var y = random.getRandom(0, map.offsetHeight / this.height); this.x = x * this.width; this.y = x * this.height; dvObj.style.left = this.x + "px"; dvObj.style.top = this.y + "px"; } window.Food = Food; }()); var food = new Food(); food.init();