微信小程序中实现进入页面时数字跳动效果(自定义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"/>
相关推荐
鸭鸭梨吖4 小时前
微信小程序---下拉框
微信小程序·小程序
CRMEB定制开发5 小时前
CRMEB Pro版前端环境配置指南
前端·微信小程序·uni-app·商城源码·微信商城·crmeb
mon_star°7 小时前
搭建一款结合传统黄历功能的日历小程序
微信·微信小程序·小程序·微信公众平台
The_era_achievs_hero7 小时前
微信小程序91~100
微信小程序·小程序
假装我不帅7 小时前
微信小程序下拉加载更多实现
微信小程序·小程序
高压锅_12208 小时前
Cursor+Coze+微信小程序实战: AI春联生成器
人工智能·微信小程序·notepad++
2301_805962938 小时前
微信小程序控制空调之微信小程序篇
微信小程序·小程序
Ama_tor13 小时前
mini-program01の系统认识微信小程序开发
微信小程序·小程序
毛毛三由1 天前
基于svga+uniapp的微信小程序动画组件开发指南
微信小程序·uni-app·notepad++