微信小程序中实现进入页面时数字跳动效果(自定义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_915918414 小时前
Fiddler中文版全面评测:功能亮点、使用场景与中文网资源整合指南
android·ios·小程序·https·uni-app·iphone·webview
说私域5 小时前
从品牌附庸到自我表达:定制开发开源AI智能名片S2B2C商城小程序赋能下的营销变革
人工智能·小程序
難釋懷5 小时前
第一个小程序
小程序
春哥的研究所5 小时前
可视化DIY小程序工具!开源拖拽式源码系统,自由搭建,完整的源代码包分享
小程序·开源·开源拖拽式源码系统·开源拖拽式源码·开源拖拽式系统
weixin_lynhgworld5 小时前
盲盒一番赏小程序技术实现方案:高并发与防作弊的平衡之道
小程序
今日热点7 小时前
小程序主体变更全攻略:流程、资料与异常处理方案
经验分享·微信·小程序·企业微信·微信公众平台·微信开放平台
鸭鸭梨吖11 小时前
微信小程序---下拉框
微信小程序·小程序
CRMEB定制开发12 小时前
CRMEB Pro版前端环境配置指南
前端·微信小程序·uni-app·商城源码·微信商城·crmeb
mon_star°14 小时前
搭建一款结合传统黄历功能的日历小程序
微信·微信小程序·小程序·微信公众平台
The_era_achievs_hero14 小时前
微信小程序91~100
微信小程序·小程序