react-countup
地址
https://github.com/glennreyes/react-countup
https://www.npmjs.com/package/react-countup
效果
Ant Motion(动效组件)
地址
效果
纯 CSS 实现数字动画
https://css-tricks.com/animating-number-counters/
要写一个数字从 0-100 增长的动画效果,可能首先会想到用 setInterval,但是其实你可以试试 New School 的 CSS 解决方案。
示例一(手动触发)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
@property --num {
syntax: '<integer>';
initial-value: 0;
inherits: false;
}
div {
transition: --num 5s;
counter-set: num var(--num);
font: 800 40px system-ui;
}
div::after {
content: counter(num);
}
div:hover {
--num: 100;
}
body {
margin: 2rem;
}
</style>
</head>
<body>
Hover the number.
<div></div>
</body>
</html>
示例二(也可以用于 @keyframes 自动触发)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
@property --num {
syntax: '<integer>';
initial-value: 0;
inherits: false;
}
div {
animation: counter 5s infinite alternate ease-in-out;
counter-reset: num var(--num);
font: 800 40px system-ui;
padding: 2rem;
}
div::after {
content: counter(num);
}
@keyframes counter {
from {
--num: 0;
}
to {
--num: 100;
}
}
</style>
</head>
<body>
<div></div>
</body>
</html>
示例三(携带小数)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
@property --percent {
syntax: '<number>';
initial-value: 0;
inherits: false;
}
@property --temp {
syntax: '<number>';
initial-value: 0;
inherits: false;
}
@property --v1 {
syntax: '<integer>';
initial-value: 0;
inherits: false;
}
@property --v2 {
syntax: '<integer>';
initial-value: 0;
inherits: false;
}
div {
font: 800 40px monospace;
padding: 2rem;
transition: --percent 1s;
--temp: calc(var(--percent) * 100);
--v1: max(var(--temp) - 0.5, 0);
--v2: max((var(--temp) - var(--v1)) * 100 - 0.5, 0);
counter-reset: v1 var(--v1) v2 var(--v2);
}
div::before {
content: counter(v1) '.' counter(v2, decimal-leading-zero) '%';
}
</style>
</head>
<body>
<div></div>
<script>
const genNumber = () => {
document
.querySelector('div')
.style.setProperty('--percent', Math.random());
};
setInterval(genNumber, 2000);
setTimeout(genNumber);
</script>
</body>
</html>