很多大屏、官网或者展示类页面会用到数字跳动更新效果的需求,可以试试countUp插件。我这里没有放动图,具体实现效果可以搜搜,主要写一下基本用法。
countup.js是一个无依赖性、轻量级的javascript类,可用于快速创建动画,以更有趣的方式显示数字/数据。
使用:
(1) 、下载地址:
https://github.com/inorganik/CountUp.js;
(2)、 写入
- import { CountUp } from './countUp.min.js';
-
- window.onload = function () {
- var countUp = new CountUp('myElementId', 2000);
- if (!countUp.error) {
- countUp.start();
- } else {
- console.error(countUp.error);
- } }
如果script写在body最底下,那么window.onload就也不需要了。
npm install countup 进行安装依赖
import CountUp from "countup" 在页面中引入
new出CountUp构造函数后,可以传入参数,而第一个参数为元素的id,第二个为跳动的end值,第三个为{}对象,这里简单说一下第三个参数有哪些参数可以设置。
- initCountUp(dom, data) {
- let totalData = new CountUp(dom, data, {
- startVal: 0, // 跳动起始数字
- useGrouping: false, // 是否开启逗号,默认true
- });
- totalData.start(); // 启动 start函数支持传入一个回调函数作为参数
- }
{
startVal: 20,
decimalPlaces: 2,
duration: 5,
useGrouping: true,
useEasing: true,
smartEasingThreshold: 500,
smartEasingAmount: 300,
separator: ',',
decimal: '.',
prefix: '¥',
suffix: '元',
numerals: ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹']
}
key | value | 说明 |
---|---|---|
startVal | number | 跳动起始数字 |
decimalPlaces | number | 小数位,整数自动添.00 |
duration | number | 动画持续时间 |
useGrouping | boolean | 是否开启逗号,默认true |
useEasing | boolean | 动画缓动效果(ease),默认true |
smartEasingThreshold | number | 大于这个数值的值开启滑缓动v |
smartEasingAmount | number | amount to be eased for numbers above threshold (333) |
separator | strng | 分割用的符号 |
decimal | string | 小数分割符合 |
prefix | string | 数字开头添加固定字符 |
suffix | string | 数字末尾添加固定字符 |
numerals | Array | 替换从0到9对应的字,也就是自定数字字符了,数组存储 |
需要注意的是,现在插件已经不会自动绑定scroll事件了,也就是说,数字跳动触发是需要自己手动的,这也方便我们自定义了,不会被预定义的方法搞得手忙脚乱 。