前端 1随机产生50个随机颜色的球2随机产生背景颜色3每秒一次
- 首先创建一个HTML文件,引入CSS和JavaScript文件。
- 在HTML中创建一个div容器,用于显示随机颜色的球。
- 在JavaScript中定义一个函数,用于生成随机颜色的球。
- 使用setInterval()方法每秒调用一次该函数。
- 在函数中使用Math.random()方法生成随机颜色,并将其应用到球的背景色中。
- 创建50个球,将它们添加到容器中。
HTML代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>随机颜色的球</title>
<style>
#container {
width: 500px;
height: 500px;
margin: 0 auto;
background-color: #333;
position: relative;
}
.ball {
width: 50px;
height: 50px;
border-radius: 50%;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="random-color-balls.js"></script>
</body>
</html>
JavaScript代码:
function generateRandomColor() {
var color = '#';
for (var i = 0; i < 6; i++) {
color += Math.floor(Math.random() * 16).toString(16);
}
return color;
}
function createBalls() {
var container = document.getElementById('container');
container.innerHTML = '';
for (var i = 0; i < 50; i++) {
var ball = document.createElement('div');
ball.className = 'ball';
ball.style.backgroundColor = generateRandomColor();
ball.style.top = Math.floor(Math.random() * 450) + 'px';
ball.style.left = Math.floor(Math.random() * 450) + 'px';
container.appendChild(ball);
}
}
setInterval(createBalls, 1000);
在CSS中,我们定义了容器的大小和背景色,并将球的样式定义为圆形。在JavaScript中,我们定义了两个函数:generateRandomColor()和createBalls()。generateRandomColor()用于生成随机颜色,createBalls()用于创建50个球,并将它们添加到容器中。我们使用setInterval()方法每秒调用一次createBalls()函数,以生成不同的随机颜色的球
原文地址: https://www.cveoy.top/t/topic/eC61 著作权归作者所有。请勿转载和采集!