渲染数组数据
2024年12月9日大约 1 分钟
练习页面容器创建配合
- 主要学习 使用 javascript 渲染数组数据
完整网页
<!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>
body {
font-family: Arial, sans-serif;
margin: 20px;
text-align: center;
}
.date_number {
padding: 5px;
font-size: 16px;
width: 200px;
}
.cyc {
padding: 6px 12px;
font-size: 16px;
margin-left: 10px;
cursor: pointer;
}
.box {
margin-top: 20px;
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 10px;
align-items: flex-end;
}
.box div {
display: flex;
flex-direction: column;
align-items: center;
}
.box span {
display: inline-block;
width: 40px;
background-color: #007bff;
color: white;
text-align: center;
line-height: 1.5;
border-radius: 5px;
margin-bottom: 5px;
}
.box h4 {
margin: 0;
font-size: 14px;
color: #333;
}
</style>
</head>
<body>
<input class="date_number" type="number" placeholder="输入数据">
<button class="cyc">抄</button>
<div class="box"></div>
<script>
const btn = document.querySelector('.cyc')
const date_number = document.querySelector('.date_number')
const box = document.querySelector('.box')
let arr = []
btn.addEventListener('click', async function click_btn() {
if (date_number.value.trim() === '' || isNaN(+date_number.value) ){ // 判断是否有输入,与正确
alert('确保正确的数')
date_number.value = null // 清空输入框
return
}
await write_arr(+date_number.value)
date_number.value = null
} )
async function write_arr(params) {
arr.push(params)
console.log(params)
console.log(arr)
await updateBox()
}
async function updateBox() {
box.innerHTML = ""
arr.forEach((num, index) => {
const item = document.createElement('div'); // 创建一个 div 容器
const bar = document.createElement('span'); // 创建一个 span 元素,用于表示条形图
const label = document.createElement('h4'); // 创建一个 h4 元素,用于显示索引值c
bar.style.height = `${num}px`; // 创建一个 h4 元素,用于显示索引值
bar.textContent = num; // 在条形图中显示数值
label.textContent = index + 1; // 设置索引,从 1 开始
item.appendChild(bar); // 把条形图添加到容器中
item.appendChild(label); // 把序号添加到容器中
box.appendChild(item); // 把整个容器添加到页面中的 box 容器
});
}
</script>
</body>
</html>