<!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>
点击随机产生随机小球
最新推荐文章于 2022-09-03 11:47:22 发布