初学JS—随机方块

10个小方块颜色 位置随机变化
在这里插入图在这里插入图片描述片描述在这里插入图片描述
style.css文件:

#container{
	width: 800px;
	height: 600px;
	background-color:lightgrey;
	position: relative;
}

tools.js文件:

var tools = {
	getRandom: function(min,max){
		return Math.floor(Math.random()*(max - min + 1)) + min;
	}
}

box.js文件:

function Box(parent,options){
	var options = options || {};
	this.backgroundColor = options.backgroundColor || 'red';
	this.width = options.width || 20 ;
	this.height = options.height || 20;
	this.x = options.x || 0 ;
	this.y = options.y || 0 ;
	this.position = 'absolute';
	this.parent = parent;
	
	this.div = document.createElement("div");
	parent.appendChild(this.div);
	
	this.init();
	this.getRandomXY();
}

Box.prototype.init = function(){
	var div = this.div;
	div.style.backgroundColor = this.backgroundColor;
	div.style.width = this.width + 'px';
	div.style.height = this.height + 'px';
	div.style.left = this.x + 'px';
	div.style.top =  this.y + 'px';
	div.style.position = 'absolute';	
}

Box.prototype.getRandomXY = function(){
	var x = tools.getRandom(0, this.parent.offsetWidth/this.width - 1);
	var y = tools.getRandom(0, this.parent.offsetHeight/this.height - 1);
	
	this.div.style.left = x*this.width + 'px';
	this.div.style.top = y*this.height + 'px';
}

index.html文件:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<link rel="stylesheet" type="text/css" href="css/style.css"/>
		<script src = "js/tools.js"></script>
		<script src = "js/box.js"></script>
		<title>随机方块</title>
	</head>
	<body>
		<div id="container"></div>
		<script>
			
				var parent = document.getElementById("container");
				function flash(){
					var array = parent.children;//将要删除的小box放入数组中
					console.log(array);
					if(parent.children.length > 0){
						for(var i = 0; i < 10; i++){
							 parent.removeChild(array[0]); 
						}
					}
					if(parent.children.length == 0){
						for(var i = 0; i < 10; i++){	
							var box = new Box(parent,{backgroundColor:'rgb(' + tools.getRandom(0,255) + ',' +tools.getRandom(0,255) + ',' + tools.getRandom(0,255) + ')'});
						}
					}
				}
				setInterval(flash,500);
		</script>
	</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值