微信小程序中实现进入页面时数字跳动效果(自定义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"/>
相关推荐
qwfy9 小时前
我从瑞幸咖啡小程序里,拆出了一套 22 个组件的开源 UI 库
微信小程序·开源
2501_9159214311 小时前
苹果iOS应用开发上架与推广完整教程
android·ios·小程序·https·uni-app·iphone·webview
2501_9151063212 小时前
HTTP和HTTPS协议工作原理及安全性全面解析
android·ios·小程序·https·uni-app·iphone·webview
禾高网络13 小时前
长护险智慧服务平台:科技赋能长期照护保障体系
大数据·人工智能·科技·小程序
笨笨狗吞噬者15 小时前
小程序包体积分析利器 -- vite-plugin-component-insight
前端·微信小程序·uni-app
杰建云16717 小时前
小程序转化率低的核心原因是什么?
小程序·小程序制作
中国胖子风清扬17 小时前
基于GPUI框架构建现代化待办事项应用:从架构设计到业务落地
java·spring boot·macos·小程序·rust·uni-app·web app
Greg_Zhong18 小时前
微信小程序中使用canvas中绘制的页面,切换字体的几种实践方式
微信小程序·腾讯云cos·canvas页面切换字体
weikecms18 小时前
外卖CPS小程序哪家系统比较完善
小程序
绝世唐门三哥1 天前
uniapp系列-uniappp都有哪些生命周期?
vue.js·小程序·uniapp