微信小程序中实现进入页面时数字跳动效果(自定义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"/>
相关推荐
HERR_QQ16 小时前
【unify】unify的微信小程序开发学习 (to be continued)
学习·微信小程序·小程序
racerun1 天前
小程序导航设置更多内容的实现方法
小程序
说私域1 天前
基于开源AI智能名片链动2+1模式S2B2C商城小程序的超级文化符号构建路径研究
人工智能·小程序·开源
mg6681 天前
微信小程序入门实例_____快速搭建一个快递查询小程序
微信小程序·小程序
程序员柳1 天前
基于微信小程序的校园二手交易平台、微信小程序校园二手商城源代码+数据库+使用说明,layui+微信小程序+Spring Boot
数据库·微信小程序·layui
Jyywww1211 天前
微信小程序学习笔记
笔记·学习·微信小程序
The_era_achievs_hero1 天前
微信小程序41~50
微信小程序·小程序
走,带你去玩2 天前
uniapp 微信小程序水印
微信小程序·小程序·uni-app
是一碗螺丝粉2 天前
🔥 微信H5视频自动播放终极秘籍:WeixinJSBridge竟是官方“通行证”?
微信小程序