文章介绍了如何在微信小程序中实现进入页面时的数字跳动效果,通过自定义一个名为`animate-numbers`的组件来实现这一功能,本文给大家介绍的非常详细,感兴趣的朋友一起看看吧
目录
1. 组件定义,新建animate-numbers组件1.1 index.js1.2 wxml1.3 wxss2. 使用组件微信小程序中实现进入页面时数字跳动效果
1. 组件定义,新建animate-numbers组件
1.1 index.js
// components/animate-numbers/index.jsComponent({ 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
<view>{{displayNumber}}</view>
1.3 wxss
page { font-size: 48rpx; font-weight: bold;}
2. 使用组件
"animate-numbers": "../../../components/animate-numbers/index"
<animate-numbers number="{{attendanceInfo.month_avg_days}}" duration="1000"/>