countup.js实现数字动态叠加效果

作者:青山有信

时间:2026-10-23

浏览:514

本文介绍countup.js轻量级JavaScript库,用于实现数字动态叠加动画。详细解析startVal、endVal等核心参数配置,提供基础用法及Vue环境下的集成代码示例,帮助开发者快速实现数值变化效果。

文章目录

countup.js简介与参数配置

本文分享了使用countup.js实现数字动态叠加效果的具体代码,供读者参考。

countup.js简介与参数配置

CountUp.js是一个无依赖、轻量级的JavaScript类,旨在以更具吸引力的动画方式展示数值数据。虽然名称为countUp,但它支持双向变化,具体方向由传递的startVal和endVal参数决定,并可结合滚动事件进行判断。

该库支持以下可配置参数:

  • target:指定目标元素的ID;
  • startVal:设置动画起始数值;
  • endVal:设置动画结束数值;
  • decimals:定义小数位数,默认为0;
  • duration:设定动画持续时间(秒),默认为2。

以下是具体的使用示例:


var options = {

  useEasing: true, 
  useGrouping: true, 
  separator: ',', 
  decimal: '.', 
};
var demo = new CountUp('myTargetElement', 0, 4068, 0, 2.5, options);
if (!demo.error) {
  demo.start();
} else {
console.error(demo.error);

安装与Vue集成示例

安装方法如下:


npm i countup.js

在Vue项目中的使用方式:


<template>
 <h1><span
 ref='countup'
 class="text"
 ></span>
 </h1>
</template>

<script>
import { CountUp } from 'countup.js'
export default {
 name: 'Countup',
 data () {
 return {
 options: {
 startVal: 1000
 },
 endCount: 2019
 }
 },
 mounted () {
 this.initCountUp()
 },
 methods: {
 initCountUp () {
 let demo = new CountUp(this.$refs.countup, this.endCount, this.options)
 if (!demo.error) {
 demo.start()
 } else {
 console.error(demo.error)
 }
 }
 }
}
</script>

<style lang="less" scoped>
.text {
 color: #4d63bc;
 font-size: 16px;
}
</style>

演示地址:countUp.js

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章