随机方块
十个方块在范围内,随机浮动
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;
}
来源:CSDN
作者:qq_38427709
链接:https://blog.csdn.net/qq_38427709/article/details/103584805