微信小程序中实现进入页面时数字跳动效果(自定义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"/>
相关推荐
源码_V_saaskw3 小时前
JAVA国际版二手交易系统手机回收好物回收发布闲置商品系统源码支持APP+H5
java·开发语言·微信·智能手机·微信小程序·小程序
韩立学长4 小时前
【开题答辩实录分享】以《智慧校园勤工俭学信息管理系统的设计与实现》为例进行答辩实录分享
vue.js·spring boot·微信小程序
余道各努力,千里自同风7 小时前
小程序中获取元素节点
前端·小程序
笨笨狗吞噬者8 小时前
【uniapp】小程序体积优化,分包异步化
前端·微信小程序·uni-app
00后程序员张8 小时前
iOS 26 开发者工具推荐,构建高效调试与性能优化工作流
android·ios·性能优化·小程序·uni-app·iphone·webview
计算机学姐8 小时前
基于微信小程序的奶茶店点餐平台【2026最新】
java·vue.js·spring boot·mysql·微信小程序·小程序·mybatis
性野喜悲9 小时前
<script setup lang=“ts“>+uniapp实现轮播(swiper)效果
前端·javascript·vue.js·小程序·uni-app
2501_916008899 小时前
iOS 26 文件导出与数据分析,多工具组合下的开发者实践指南
android·macos·ios·小程序·uni-app·cocoa·iphone
2501_916008899 小时前
iOS混淆实战用多工具组合把IPA加固做成可复用的工程能力(iOS混淆 IPA加固 无源码混淆
android·ios·小程序·https·uni-app·iphone·webview