JS高級----------------->產生隨機小方塊的方法


<!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>
    //產生隨機數對象的
    (function (window) {
        function Random() {
        }

        Random.prototype.getRandom = function (min, max) {
            return Math.floor(Math.random() * (max - min) + min);
        };
        //把局部對象暴露給window頂級對象,就成了全局的對象
        window.Random = new Random();
    })(window);//自調用構造函數的方式,分號一定要加上


    //產生小方塊對象
    (function (window) {
        //console.log(Random.getRandom(0,5));
        //選擇器的方式來獲取元素對象
        var map = document.querySelector(".map");

        //食物的構造函數
        function Food(width, height, color) {
            this.width = width || 20;//默認的小方塊的寬
            this.height = height || 20;//默認的小方塊的高
            //橫坐標,縱坐標
            this.x = 0;//橫坐標隨機產生的
            this.y = 0;//縱坐標隨機產生的
            this.color = color;//小方塊的背景顏色
            this.element = document.createElement("div");//小方塊的元素
        }

        //初始化小方塊的顯示的效果及位置---顯示地圖上
        Food.prototype.init = function (map) {
            //設置小方塊的樣式
            var div = this.element;
            div.style.position = "absolute";//脫離文檔流
            div.style.width = this.width + "px";
            div.style.height = this.height + "px";
            div.style.backgroundColor = this.color;
            //把小方塊加到map地圖中
            map.appendChild(div);
            this.render(map);
        };
        //產生隨機位置
        Food.prototype.render = function (map) {
            //隨機產生橫縱坐標
            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";
        };

        //實例化對象
        var fd = new Food(20, 20, "green");
        fd.init(map);
        console.log(fd.x + "====" + fd.y);
    })(window);
</script>
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM