日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

js实现随机生成小方块

發布時間:2025/3/21 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 js实现随机生成小方块 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
<!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;/*因為小方塊要脫標*/position: relative;}</style> </head> <body> <div id="map"></div><script>//1.產生隨機數的對象 (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.產生小方塊的對象 (function () {var map = document.getElementById("map");//小方塊的構造函數function Food(width,height, color, x, y) {this.width = width || 20;//設置默認的小方塊的寬度this.height = height ||20;this.color = color || "pink";//需要隨機產生的left和top值this.x = x || 0;this.y = y || 0;//創建一個div盒子-->即小方塊this.element = document.createElement("div");}//初始化小方塊顯示的位置 Food.prototype.init = function () {//1.設置小方塊的樣式 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.位置隨機this.render();}//添加位置隨機的方法 Food.prototype.render = function () {// 0-40 --->隨機區間0-39this.x = random.getRandom(0,map.offsetWidth/this.width )* this.width;this.y = random.getRandom(0,map.offsetHeight/this.height )* this.height;//設置小方塊的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>

?

轉載于:https://www.cnblogs.com/Ironman725/p/10946432.html

總結

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

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。