微信小程序数字滚动动画
V1nc4nt丶 人气:0效果图
实现思路
1、为了实现数字的无限滚动效果,每个数字框的内部,其实包含了两组0~9的view,每个View的高度都一样
2、数字框内使用绝对定位,通过调整top位置,显示出指定的数字
3、使用transtion动画,top发生变化时就会滚动,然后通过指定动画的delay、duration,使数字之间延时动画
项目代码
js文件
// components/scroll-number/index.js Component({ externalClasses: ['container-class', 'item-class', 'dot-class'], properties: { value: { type: String, value: '' }, /** 一次滚动耗时 单位ms */ duration: { type: Number, value: 1600 }, /** 每个数字之间的延迟滚动 */ delay: { type: Number, value: 200 } }, data: { valArr: [], aniArr: [], // 动画列表,和valArr对应 numArr: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], // 所有数字 itemHeight: 0 // 数字项的高度 }, observers: { value: function (newVal) { // 监听value变化,格式化为valArr let valArr = [] if (newVal) { valArr = newVal.split('').map(o => { return { val: o, isNaN: isNaN(o)} }) } this.setData({ valArr: valArr }) this.getNumberHeight() } }, methods: { /** 计算数字高度 */ getNumberHeight() { if (this.data.itemHeight > 0) { this.startScrollAni() return } const query = this.createSelectorQuery() query.select('.number-item').boundingClientRect() query.exec((res) => { this.setData({ itemHeight: res[0].height }) this.startScrollAni() }) }, /** 开始滚动动画 */ startScrollAni() { if (this.data.itemHeight <= 0) return const aniArr = [] this.data.valArr.forEach((item, index) => { if(!item.isNaN) { aniArr.push(`transition-delay: ${this.data.delay * index}ms; top: ${-this.data.itemHeight * (this.data.numArr[parseInt(item.val)] + 10)}px;`) } else { aniArr.push(null) } }) this.setData({ aniArr: aniArr }) } } })
wxml文件
<!--components/scroll-number/index.wxml--> <view class="scroll-number container-class"> <block wx:for="{{valArr}}" wx:key="index"> <view wx:if="{{item.isNaN}}" class="scroll-number-item number-dot dot-class">{{item.val}}</view> <view wx:else class="scroll-number-item number-item item-class"> <view class="scroll-ani" style="transition-duration: {{duration}}ms; {{aniArr[index]}}"> <view wx:for="{{numArr}}" wx:for-item="num" wx:for-index="idx" wx:key="idx" class="num{{num}}">{{num}}</view> <view wx:for="{{numArr}}" wx:for-item="num" wx:for-index="idx" wx:key="idx" class="num{{num}}">{{num}}</view> </view> </view> </block> </view>
wxss文件
/* components/scroll-number/index.wxss */ .scroll-number { display: flex; align-items: flex-end; } .scroll-number-item { color: #0079FE; font-size: 48rpx; font-weight: bold; margin: 0 24rpx; font-family: Microsoft YaHei; } .number-item { background-color: rgba(0, 121, 254, 0.2); border-radius: 8rpx; width: 56rpx; height: 72rpx; line-height: 72rpx; overflow: hidden; text-align: center; position: relative; } .number-dot { margin: 0 12rpx; } .scroll-ani { position: absolute; top: 0; left: 0; width: 100%; height: 100%; transition: all 2s ease-in-out 0s; }
加载全部内容