微信小程序中实现进入页面时数字跳动效果(自定义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"/>
相关推荐
2501_9151063210 小时前
iPhone 文件管理,如何进行应用沙盒文件查看
android·ios·小程序·https·uni-app·iphone·webview
说私域10 小时前
以非常6+1体系为支撑 融入AI智能名片商城小程序 提升组织建设效能
大数据·人工智能·小程序·流量运营·私域运营
是梦终空10 小时前
计算机毕业设计267—基于Springboot+vue3+小程序的医院挂号系统(源代码+数据库)
spring boot·小程序·vue·毕业设计·课程设计·医院挂号系统·源代码
kyh100338112012 小时前
微信小游戏《找茬找汉字闯关王》源码赠送
microsoft·微信·微信小程序·微信小游戏·找茬小游戏·微信找茬消除
码云数智-园园12 小时前
小程序制作平台有哪些?2026微信小程序制作平台综合评测
微信小程序
低代码布道师14 小时前
【教培管家】小程序实战(八)——我的课表
低代码·小程序·云开发
码云数智-大飞14 小时前
小程序快速开发平台有哪些?微信小程序制作平台综合评测
微信小程序
一匹电信狗15 小时前
【Linux我做主】从 fopen 到 open:Linux 文件 I/O 的本质与内核视角
linux·运维·服务器·c++·ubuntu·小程序·开源
2501_9159214316 小时前
Fastlane 结合 AppUploader 来实现 CI 集成自动化上架
android·运维·ci/cd·小程序·uni-app·自动化·iphone
云游云记16 小时前
vue2 vue3 uniapp (微信小程序) v-model双向绑定
微信小程序·uni-app·vue