需求:
-
允许用户输入要生成的柱状图数量
-
随机生成柱状图的每个柱子的高度
代码部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 1200px;
height: 200px;
border: 1px solid #1a1;
margin: 100px auto;
display: flex;
justify-content: space-evenly;
align-items: flex-end;
}
</style>
</head>
<body>
</div>
<script>
// 动态生成柱状图
/*
思路分析
1. 创建大盒子的一部分:<div class="box">
2. 获取柱子的数量:用户输入
3. 求出柱子的宽度:let width = 1200 / (2 * 柱子数量 + 1)
4. 生成小的div(柱子):for循环
4.1 高度随机:Math.ceil(Math.random() * 200)
4.2 颜色随机:rgb(三个随机)
4.3 生成div:样式写入,行内:style,模板字符串将随机数据放到对应的位置
5. 关闭大盒子:</div>
*/
// 思路分析
// 1. 创建大盒子的一部分:<div class="box">
document.write(`<div class="box">`)
// 2. 获取柱子的数量:用户输入
let num = +prompt('请输入柱子数量');
// 3. 求出柱子的宽度:let width = 1200 / (2 * 柱子数量 + 1)
let width = 1200 / (2 * num + 1);
// 4. 生成小的div(柱子):for循环
for (let i = 1; i <= num; i++) {
// 4.1 高度随机:Math.ceil(Math.random() * 200)
// 4.2 颜色随机:rgb(三个随机)
// 4.3 生成div:样式写入,行内:style,模板字符串将随机数据放到对应的位置
let height = Math.ceil(Math.random() * 200);
let r = Math.ceil(Math.random() * 255);
let g = Math.ceil(Math.random() * 255);
let b = Math.ceil(Math.random() * 255);
document.write(` <div style= "width:${width}px;height:${height}px;background-color:rgb(${r},${g},${b})"> </div> `)
}
// 5. 关闭大盒子:</div>
document.write(`</div>`)
</script>
</body>
</html>
输入想要的数量

效果图

本文介绍了一种使用HTML和JavaScript动态生成随机高度和颜色的柱状图的方法。用户可以输入想要显示的柱状图数量,系统会自动计算每个柱子的宽度并随机分配高度及颜色。
1960

被折叠的 条评论
为什么被折叠?



