注册
web

前端使用CountUp.js制作数字动画效果的教程

在现代网页设计中,动态数字展示能够显著提升用户体验,吸引访客注意力。无论是数据统计、销售数字还是还是评分展示,平滑的数字增长动画都能让信息传递更加生动。CountUp.js 正是一款专门用于创建这种数字动画效果的轻量级 JavaScript 库,本文将详细介绍其使用方法与技巧。


1. 前言


CountUp.js 是一个零依赖的 JavaScript 库,用于创建从一个数字平滑过渡到另一个数字的动画效果。它体积小巧(压缩后仅约 3KB),使用简单,且高度可定制,能够满足各种数字动画需求。


CountUp.js 的特点



  • 零依赖,无需引入其他库
  • 轻量级,加载迅速
  • 高度可配置(动画时长、延迟、小数位数等)
  • 支持多种 easing 动画效果
  • 支持暂停、恢复、重置等控制
  • 兼容所有现代浏览器

2. 快速开始


CountUp.js 有多种引入方式,可根据项目需求选择:


1. 通过 npm 安装


npm install countup.js

然后在项目中导入:


import CountUp from 'countup.js';

2. 直接引入 CDN


<script src="https://cdn.jsdelivr.net/npm/countup.js@2.0.8/dist/countUp.umd.min.js">script>

3. 下载源码


GitHub 仓库 下载源码,直接引入本地文件。


2.1. 基本用法


使用 CountUp.js 只需三步:



  1. 在 HTML 中准备一个用于显示数字的元素


<div id="counter">div>


  1. 初始化 CountUp 实例

// 获取 DOM 元素
const element = document.getElementById('counter');

// 目标数值
const target = 1000;

// 创建 CountUp 实例
const countUp = new CountUp(element, target);


  1. 启动动画

// 检查是否初始化成功,然后启动动画
if (!countUp.error) {
countUp.start();
} else {
console.error(countUp.error);
}

3. 配置选项


CountUp.js 提供了丰富的配置选项,让你可以精确控制动画效果:


const options = {
startVal: 0, // 起始值,默认为 0
duration: 2, // 动画时长(秒),默认为 2
decimalPlaces: 0, // 小数位数,默认为 0
useGr0uping: true, // 是否使用千位分隔符,默认为 true
useEasing: true, // 是否使用缓动效果,默认为 true
smartEasingThreshold: 999, // 智能缓动阈值
smartEasingAmount: 300, // 智能缓动数量
separator: ',', // 千位分隔符,默认为 ','
decimal: '.', // 小数点符号,默认为 '.'
prefix: '', // 数字前缀
suffix: '', // 数字后缀
numerals: [] // 数字替换数组,用于本地化
};

// 使用配置创建实例
const countUp = new CountUp(element, target, options);

3.1. 示例:带前缀和后缀的动画


// 显示"$1,234.56"的动画
const options = {
startVal: 0,
duration: 3,
decimalPlaces: 2,
prefix: '$',
suffix: ''
};

const countUp = new CountUp(document.getElementById('price'), 1234.56, options);
countUp.start();

4. 高级控制方法


CountUp.js 提供了多种方法来控制动画过程:


// 开始动画
countUp.start();

// 暂停动画
countUp.pauseResume();

// 重置动画
countUp.reset();

// 更新目标值并重新开始动画
countUp.update(2000);

// 立即完成动画
countUp.finish();

4.1. 示例:带回调函数的动画


// 动画完成后执行回调函数
countUp.start(() => {
console.log('动画完成!');
// 可以在这里执行后续操作
});

5. 实际应用场景


下面是实际应用场景的模拟:


5.1. 数据统计展示


<div class="stats">
<div class="stat-item">
<h3>用户总数h3>
<div class="stat-value" id="users">div>
div>
<div class="stat-item">
<h3>总销售额h3>
<div class="stat-value" id="sales">div>
div>
<div class="stat-item">
<h3>转化率h3>
<div class="stat-value" id="conversion">div>
div>
div>

<script>
// 初始化多个计数器
const usersCounter = new CountUp('users', 12500, { suffix: '+' });
const salesCounter = new CountUp('sales', 458920, { prefix: '$', decimalPlaces: 0 });
const conversionCounter = new CountUp('conversion', 24.5, { suffix: '%', decimalPlaces: 1 });

// 同时启动所有动画
document.addEventListener('DOMContentLoaded', () => {
usersCounter.start();
salesCounter.start();
conversionCounter.start();
});
script>

5.2. 滚动触发动画


结合 Intersection Observer API,实现元素进入视口时触发动画:


<div id="scrollCounter" class="counter">div>

<script>
// 创建计数器实例但不立即启动
const scrollCounter = new CountUp('scrollCounter', 5000);

// 配置交叉观察器
const observer = new IntersectionObserver((entries) => {
entries.
forEach(entry => {
if (entry.isIntersecting) {
// 元素进入视口,启动动画
scrollCounter.
start();
// 只观察一次
observer.
unobserve(entry.target);
}
});
});

// 观察目标元素
observer.
observe(document.getElementById('scrollCounter'));
script>

5.3. 结合按钮控制


<div id="controlledCounter">div>
<button id="startBtn">开始button>
<button id="pauseBtn">暂停button>
<button id="resetBtn">重置button>
<button id="updateBtn">更新到 2000button>

<script>
const counter = new CountUp('controlledCounter', 1000);

// 按钮事件监听
document.getElementById('startBtn').addEventListener('click', () => {
counter.start();
});

document.getElementById('pauseBtn').addEventListener('click', () => {
counter.pauseResume();
});

document.getElementById('resetBtn').addEventListener('click', () => {
counter.reset();
});

document.getElementById('updateBtn').addEventListener('click', () => {
counter.update(2000);
});
script>

6.自定义缓动函数


CountUp.js 允许你自定义缓动函数,创建独特的动画效果:


// 自定义缓动函数
function myEasing(t, b, c, d) {
// t: 当前时间
// b: 起始值
// c: 变化量 (目标值 - 起始值)
// d: 总时长
t /= d;
return c * t * t * t + b;
}

// 使用自定义缓动函数
const options = {
duration: 2,
easingFn: myEasing
};

const countUp = new CountUp(element, target, options);
countUp.start();

7. 常见问题与解决方案


下面是一些常见问题与解决方案:


7.1. 动画不生效



  • 检查元素是否正确获取
  • 确保目标值大于起始值(如需从大到小动画,可设置 startVal 大于 target)
  • 检查控制台是否有错误信息

7.2. 数字格式问题



  • 使用 separator 和 decimal 选项配置数字格式
  • 对于特殊数字系统,使用 numerals 选项进行替换

7.3. 性能问题



  • 避免在同一页面创建过多计数器实例
  • 对于非常大的数字,适当增加动画时长
  • 考虑使用滚动触发,而非页面加载时同时启动所有动画

8. 总结


CountUp.js 是一个简单而强大的数字动画库,能够为你的网站增添专业感和活力。它的轻量级特性和丰富的配置选项使其适用于各种场景,从简单的数字展示到复杂的数据可视化。


通过本文介绍的基础用法和高级技巧,你可以轻松实现各种数字动画效果,提升用户体验。无论是个人博客、企业官网还是电商平台,CountUp.js 都能成为你前端工具箱中的得力助手。


参考资源






作者:鹏多多
来源:juejin.cn/post/7542403996917989422

0 个评论

要回复文章请先登录注册