1. 随机产生50个随机颜色的球

HTML结构:

<div id="container"></div>

CSS样式:

#container {
  width: 500px;
  height: 500px;
  position: relative;
}

.ball {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  position: absolute;
}

JavaScript代码:

// 获取容器元素
const container = document.getElementById('container');

// 生成50个随机颜色的球
for (let i = 0; i < 50; i++) {
  // 生成随机颜色
  const color = '#' + Math.floor(Math.random() * 16777215).toString(16);
  
  // 创建球元素
  const ball = document.createElement('div');
  ball.className = 'ball';
  ball.style.backgroundColor = color;
  
  // 随机生成球的位置
  const x = Math.floor(Math.random() * (container.offsetWidth - ball.offsetWidth));
  const y = Math.floor(Math.random() * (container.offsetHeight - ball.offsetHeight));
  ball.style.left = x + 'px';
  ball.style.top = y + 'px';
  
  // 将球添加到容器中
  container.appendChild(ball);
}
  1. 随机产生背景颜色

HTML结构:

<div id="container"></div>

CSS样式:

#container {
  width: 500px;
  height: 500px;
  position: relative;
}

JavaScript代码:

// 获取容器元素
const container = document.getElementById('container');

// 生成随机背景颜色
const color = '#' + Math.floor(Math.random() * 16777215).toString(16);
container.style.backgroundColor = color;
``
前端 1随机产生50个随机颜色的球2随机产生背景颜色

原文地址: https://www.cveoy.top/t/topic/eC6T 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录