点击随机产生随机小球

<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<title>很多小球</title>
	<style type="text/css">
		* {
			margin: 0;
			padding: 0;
		}

		.c {
			display: flex;
			justify-content: center;
			align-items: center;
			border-radius: 50%;
			font-size: 20px;
			position: absolute;
			left: 0;
			top: 0;
		}

		#txt {
			width: 90px;
			height: 90px;
			border: 2px #f00 solid;
			font-size: 30px;
			text-align: center;
			line-height: 90px;
			margin-top: 30px;
		}
	</style>
</head>

<body>
	<input type="number" id="num" value="" />
	<button type="button" id="btn">创建小球</button> <br />
	<input type="color" id="col" value="" /> <br />
	<input type="number" id="r" value="0" /> <br />
	<input type="number" id="g" value="0" /> <br />
	<input type="number" id="b" value="0" /> <br />

	<div id="txt"></div>
</body>

</html>
<script type="text/javascript">
	function rand(m, n) {
		return Math.floor(Math.random() * (n - m + 1) + m);
	}

	function randCol() {
		var r = rand(0, 255);
		var g = rand(0, 255);
		var b = rand(0, 255);

		return 'rgb(' + r + ',' + g + ',' + b + ')';
	}

	function $(ele) {
		return document.querySelector(ele);
	}

	// 设置当前操作小球的下标
	var index = 0;

	//点击小球触发的方法
	function clickBall() {
		$('#txt').innerHTML = this.innerHTML;
		this.style.background = $('#col').value;
		index = this.innerHTML - 1;
	}

	// 改变拾色器
	$('#col').onchange = function () {
		var balls = document.querySelectorAll('.c');
		balls[index].style.background = this.value;
	};

	// 点击小球创建
	$('#btn').onclick = function () {
		// 创建之前先清空老球
		var cs = document.querySelectorAll('.c');
		for (var i = cs.length - 1; i >= 0; i--) {
			document.body.removeChild(cs[i]);
		}


		var val = $('#num').value;
		if (val) {
			//创建小球
			for (var i = 0; i < val; i++) {
				var cir = document.createElement('div');
				cir.innerHTML = i + 1;
				cir.className = 'c';
				// 获取元素的宽高
				var w = rand(30, 80);
				cir.style.width = cir.style.height = w + 'px';

				cir.style.background = randCol();

				// 获取屏幕的最大宽度和最大高
				var W = window.innerWidth;
				var H = window.innerHeight;

				cir.style.left = rand(0, W - w) + 'px';

				cir.style.top = rand(0, H - w) + 'px';

				//绑定事件
				cir.onclick = clickBall;

				document.body.appendChild(cir);
			}
		} else {
			alert('请输入创建个数');
		}
	};

	//修改rgb的方法
	function changeRgb() {
		var r = $('#r').value;
		var g = $('#g').value;
		var b = $('#b').value;

		var balls = document.querySelectorAll('.c');
		balls[index].style.background = 'rgb(' + r + ',' + g + ',' + b + ')';
	}
	$('#r').onchange = $('#g').onchange = $('#b').onchange = changeRgb;
</script>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值