案例效果:
随着学习的深入,以下会展示不同的实现方法,整体代码如下:
<!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>
h1 {
text-align: center;
}
.box {
display: flex;
height: 400px;
width: 800px;
margin: 0 auto;
border-bottom: 3px grey solid;
border-left: 3px grey solid;
justify-content: space-around;
/* 均匀排列弹性容器内的每个元素,且元素之间的间隔相同 */
align-items: flex-end;
/* 控制容器元素对齐的方式 */
text-align: center;
}
.box>div {
display: flex;
width: 60px;
background-color: pink;
flex-direction: column;
/* 指定内部元素在flex容器里的布局方式,定义了主轴的方向 */
justify-content: space-between;
/* 均匀排列每个元素,首个元素放在起点,最后一个元素放在终点 */
}
.box div span {
margin-top: -20px;
}
.box div h4 {
margin-bottom: -35px;
width: 70px;
margin-left: -5px;
}
</style>
</head>
<body>
<h1>季度表</h1>
<script>
// 法一
/* let height1 = prompt('请输入高度1')
let height2 = prompt('请输入高度2')
let height3 = prompt('请输入高度3')
let height4 = prompt('请输入高度4')
document.write(`
<div class="box">
<div style="height: ${height1}px;">
<span>${height1}</span>
<h4>第1季度</h4>
</div>
<div style="height: ${height2}px;">
<span>${height2}</span>
<h4>第2季度</h4>
</div>
<div style="height: ${height3}px;">
<span>${height3}</span>
<h4>第3季度</h4>
</div>
<div style="height: ${height4}px;">
<span>${height4}</span>
<h4>第4季度</h4>
</div>
</div>
`)
*/
// 法二
let arr = []
for (let i = 1; i <= 4; i++) {
arr.push(prompt(`请输入第${i}季度的数据`))
}
document.write(` <div class="box"> `)
for (i = 0; i < arr.length; i++) {
document.write(`
<div style="height: ${arr[i]}px;">
<span>${arr[i]}</span>
<h4>第${i + 1}季度</h4>
</div>
`)
}
document.write(` </div> `)
</script>
</body>
</html>
本案例在实现时还得注意了解CSS中某些属性的含义,如本案例中用到的justify-content、align-items,如若想了解其用法,可以在MDN(MDN Web Docs)中查找其使用案例。
本文中提到的知识点参考自:JS基础Day3-46-综合案例-渲染柱形图案例上_哔哩哔哩_bilibili