日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

js实现随机生成小方块

發(fā)布時間:2025/3/21 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 js实现随机生成小方块 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><style>#map{width: 800px;height: 600px;background-color: lightblue;margin: 10px auto;/*因為小方塊要脫標(biāo)*/position: relative;}</style> </head> <body> <div id="map"></div><script>//1.產(chǎn)生隨機(jī)數(shù)的對象 (function () {function Random() {}Random.prototype.getRandom = function (min, max) {return Math.floor(Math.random() * (max - min) + min);}window.random = new Random();})();console.log(random.getRandom(0,40));//2.產(chǎn)生小方塊的對象 (function () {var map = document.getElementById("map");//小方塊的構(gòu)造函數(shù)function Food(width,height, color, x, y) {this.width = width || 20;//設(shè)置默認(rèn)的小方塊的寬度this.height = height ||20;this.color = color || "pink";//需要隨機(jī)產(chǎn)生的left和top值this.x = x || 0;this.y = y || 0;//創(chuàng)建一個div盒子-->即小方塊this.element = document.createElement("div");}//初始化小方塊顯示的位置 Food.prototype.init = function () {//1.設(shè)置小方塊的樣式 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.位置隨機(jī)this.render();}//添加位置隨機(jī)的方法 Food.prototype.render = function () {// 0-40 --->隨機(jī)區(qū)間0-39this.x = random.getRandom(0,map.offsetWidth/this.width )* this.width;this.y = random.getRandom(0,map.offsetHeight/this.height )* this.height;//設(shè)置小方塊的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> </body> </html>

?

轉(zhuǎn)載于:https://www.cnblogs.com/Ironman725/p/10946432.html

總結(jié)

以上是生活随笔為你收集整理的js实现随机生成小方块的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。