需求:
-
允許用戶輸入要生成的柱狀圖數量
-
隨機生成柱狀圖的每個柱子的高度
代碼部分
<!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>
輸入想要的數量

效果圖

上一章:JavaScript入門第十章(回圈結構)
下一章:JavaScript入門第十二章(陣列回圈嵌套)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/292060.html
標籤:其他
