html
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.number {
font-size: 50px;
color: palegreen;
}
</style>
<body>
<div class="number" data-target="5000"></div>
<div class="number" data-target="1236"></div>
<div class="number" data-target="6666"></div>
</body>
<script>
// 获取所有的dom,querySelectorAll为为数组
const numbers = document.querySelectorAll('.number')
console.log("🚀 ~ file: css数字从0到指定数值.html:23 ~ numbers:", numbers)
numbers.forEach(counter => {
counter.innerText = 0;
const upDateNumber = () => {
// 获取每个类名为number的data-target,即获取最大值
const target = Number(counter.getAttribute('data-target'))
// 获取当前div的数值
const d = Number(counter.innerText)
// 设置数据增加的值,可以通过target除的数值确定怎么加数值的快慢
const increment = target / 200
// 当数字小于最大值时,执行下面的操作
if (d < target) {
// 向上取整
counter.innerText = `${Math.ceil(d + increment)}`
// 1ms重新调用,不然它会在第一次运行完就结束
setTimeout(upDateNumber, 1)
} else {
counter.innerText = target
}
}
upDateNumber()
})
</script>
</html>