JS之每次点击body生成一个背景色随机的div

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		html,body{
			height: 100%;
		}
	</style>
</head>
<body>
	
</body>
<script>
	
		var n = 0;
		document.body.onclick = function(){
			n++;
			console.log(111);
			//1.创建
			var div = document.createElement("div");
	    	
			// document.body.innerHTML += "<div></div>" ;
			var r = parseInt(Math.random()*256);
			var g = parseInt(Math.random()*256);
			var b = parseInt(Math.random()*256);
			//设置样式
			div.style.width = "100px";
			div.style.height = "100px";
			div.style.float = "left";
			div.style.backgroundColor="rgb("+r+","+g+","+b+")";
			//添加到body
			// document.body.appendChild(div);
			this.appendChild(div);//添加到末尾
			div.innerHTML = n;
	}
</script>
</html>

猜你喜欢

转载自blog.csdn.net/lanseguhui/article/details/81067823
今日推荐