js构造函数原型利用实例-随机方块

徘徊边缘 提交于 2019-12-24 07:08:18

随机方块

十个方块在范围内,随机浮动
在这里插入图片描述
Html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="./css/common.css">
    <title>Document</title>
</head>
<body>
    <div id="back">
        
    </div>
    <script src="./js/box.js"></script>
    <script src="./js/tools.js"></script>
    <script>
        tools.addBox()
    </script>
</body>
</html>

tools.js

let tools = {
    //获取随机数 从start 到 end 
    getRandom : function (start, end){
        return Math.floor(Math.random() * (end - start + 1) ) + start 
    },
    //随机颜色
    getRandomColor: function(){
        let r = this.getRandom(0,255);
        let g = this.getRandom(0,255);
        let b = this.getRandom(0,255);
        return 'rgb('+ r + ',' + g + ',' + b + ')'
    },
    //增加Box对象
    addBox : function(){
        let boxArr = []
        let _this = this 
        let box = {
        }
        for( let i = 0; i < 10; i ++){
            box = {
                background : _this.getRandomColor(),
                width: 20,
                height: 20,
            }
            boxArr[i] = new Box(box)
        }
        setInterval(randomBox,1000)
        randomBox()
        
        function randomBox(){
                for( let i = 0; i < boxArr.length; i++){
                    boxArr[i].random()
                }
        }
    }
}

box.js

let back = document.getElementById('back')
function Box(options){
    this.options = options || {}
    this.boxCom = document.createElement('div')
    back.appendChild(this.boxCom)
    this.init(this.boxCom)
}
//Box的初始化
Box.prototype.init = function(boxCom){
    boxCom.style.position = "absolute"
    boxCom.style.backgroundColor  = this.options.background || "red" 
    boxCom.style.width = (this.options.width || 20) + "px"
    boxCom.style.height =  (this.options.height || 20) + "px"
    boxCom.style.left = this.options.left || 0 +'px' 
    boxCom.style.top = this.options.top || 0 + 'px' 
}
//位置随机分配
Box.prototype.random = function(){
    this.boxCom.style.left = tools.getRandom(0, Math.floor(back.offsetWidth / this.boxCom.offsetWidth -1)) * this.boxCom.offsetWidth +'px'
    this.boxCom.style.top = tools.getRandom(0, Math.floor(back.offsetHeight/ this.boxCom.offsetHeight -1)) * this.boxCom.offsetHeight +'px'
}

css

*{
    margin: 0;
    padding: 0;
}
#back{
    width: 800px;
    height: 600px;
    background: gray;
    position: relative;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!