微信小程序中实现进入页面时数字跳动效果(自定义animate-numbers组件)

微信小程序中实现进入页面时数字跳动效果

  • [1. 组件定义,新建```animate-numbers```组件](#1. 组件定义,新建animate-numbers组件)
    • [1.1 index.js](#1.1 index.js)
    • [1.2 wxml](#1.2 wxml)
    • [1.3 wxss](#1.3 wxss)
  • [2. 使用组件](#2. 使用组件)

1. 组件定义,新建animate-numbers组件

1.1 index.js

j 复制代码
// components/animate-numbers/index.js
Component({
  properties: {
    number: {
      type: Number,
      value: 0
    },
    duration: {
      type: Number,
      value: 1000
    }
  },

  data: {
    displayNumber: 0,
    animationFrameId: null
  },

  observers: {
    'number': function (newNumber) {
      this.animateNumber(newNumber);
    }
  },

  methods: {
    animateNumber(targetNumber) {
      const start = this.data.displayNumber;//旧值
      const end = targetNumber;//新值
      const duration = this.properties.duration;
      const increment = (end - start) / (duration / 16); // 假设每秒60帧,每帧间隔约16ms
      let current = start;
      if(this.data.animationFrameId){
        clearInterval(this.data.animationFrameId);
      }

      const animate = () => {
        current += increment;
        if ((increment > 0 && current >= end) || (increment < 0 && current <= end)) {
          clearInterval(this.data.animationFrameId);
          this.setData({ displayNumber: end });
        } else {
          this.setData({ displayNumber: Math.round(current) });
        }
      };
      this.data.animationFrameId = setInterval(animate, 16);
    }
  },
  // 组件被移除时清除定时器
  detached() {
    clearInterval(this.data.animationFrameId);
  }
});

1.2 wxml

j 复制代码
<view>{{displayNumber}}</view>

1.3 wxss

j 复制代码
page {
  font-size: 48rpx;
  font-weight: bold;
}

2. 使用组件

"animate-numbers": "../../../components/animate-numbers/index"

j 复制代码
 <animate-numbers number="{{attendanceInfo.month_avg_days}}" duration="1000"/>
相关推荐
轩1154 小时前
实现仿中国婚博会微信小程序
微信小程序·小程序
知否技术8 小时前
2025微信小程序开发实战教程(一)
前端·微信小程序
喝牛奶的小蜜蜂10 小时前
个人小程序:不懂后台,如何做数据交互
前端·微信小程序·小程序·云开发
2501_9189410511 小时前
旅游微信小程序制作指南
微信小程序·小程序·旅游
全职计算机毕业设计12 小时前
SpringBoot+Mysql实现的停车场收费小程序系统+文档
spring boot·mysql·小程序
邹荣乐12 小时前
微信小程序动态tabBar实现:基于自定义组件,灵活支持不同用户角色与超过5个tab自由组合
前端·微信小程序·uni-app
半兽先生16 小时前
uniapp微信小程序视频实时流+pc端预览方案
微信小程序·uni-app·音视频
KerwinChou_CN17 小时前
自由开发者计划 004:创建一个苹果手机长截屏小程序
图像处理·算法·智能手机·小程序
Uyker17 小时前
空间利用率提升90%!小程序侧边导航设计与高级交互实现
前端·微信小程序·小程序
说私域17 小时前
基于开源AI智能名片链动2+1模式S2B2C商城小程序的生态农庄留存运营策略研究
人工智能·小程序·开源·零售