微信小程序動態數據跑馬燈組件編寫

開發必備:熟悉微信小程序組件開發css

開發思路:若是隻有一條數據,直接用css3關鍵幀動畫;若是有多條數據,則在當前動畫運動到必定時間的時候,將其數據替換掉,使之在視覺效果上有一個從下到上播放的狀態。數組循環播放的狀態是經過將當前播放元素置換到末尾實現,即經過數組元素刪除插入方法將整個數組元素串成一個閉環。css3

本例是將跑馬燈做爲一個公共組件開發的,故代碼展現爲組件形式json

目標UI:小程序

wxml文件代碼:微信小程序

<view wx:if="{{lampData && lampData.length > 0}}" class="lamp-bg">
<view wx:if="{{showItem}}" class="lamp-content box box-lr box-align-center">
<image src="{{lampData[0].avatar}}" class="avatar" />
<view class="lamp-txt">{{lampData[0].desc}}</view>
</view>
</view>

wxss文件代碼:數組

.lamp-bg {
width: 490rpx;
height: 56rpx;
background: #a50519;
border-radius: 30rpx;
overflow: hidden;
}

.lamp-content {
position: relative;
top: 60rpx;
left: 0;
animation: horseRunAnimate 2s linear infinite normal;
}

.avatar {
width: 44rpx;
height: 44rpx;
display: inline-block;
border-radius: 50%;
margin-left: 16rpx;
margin-top: 6rpx;
}

.lamp-txt {
font-size: 26rpx;
color: #fff;
display: inline;
margin-left: 6rpx;
position: relative;
top: -10rpx;
}

@keyframes horseRunAnimate {
0% {
position: relative;
top: 60rpx;
left: 0;
}

25% {
position: relative;
top: 0;
left: 0;
}
50% {
position: relative;
top: 0;
left: 0;
}
75% {
position: relative;
top: 0;
left: 0;
}
100% {
position: relative;
top: -60rpx;
left: 0;
}
}
 
json文件代碼:
{
"component": true,
"usingComponents": {}
}

js代碼:微信

let internal = '';
Component({
options: {
multipleSlots: true
},
properties: {
lampData: {
type: Array,
value: [{ avatar: '', text: 'hhhh' }, { avatar: '', desc: 'aaaa' }],
observer() {
this.startAnimate();
}
}
},
data: {
showItem: true
},
attached() {
this.setItemStatus();
},
pageLifetimes: { 
show() {
this.setData({
showItem: true
});
this.startAnimate();
},
hide() {
clearInterval(internal); // 組件所在頁面隱藏時清除setInterval,是爲了解決頁面跳轉後返回時setInterval帶來的動畫時差,在頁面上bug提現爲:兩條數據更替時有跳動現象或者數據渲染延遲
this.setData({
showItem: false
});
}
},
methods: {
setItemStatus() {
if (this.data.lampData.length > 1) {
setTimeout(() => {
this.setData({
showItem: false
});
}, 1800); // 添加showItem屬性值是爲了解決兩條數據更替是頁面延遲渲染的問題                                                  
}
},
startAnimate() {
const initArr = this.data.lampData;
if (initArr.length > 1) { // 輪播總數大於1時,才執行數組首位刪除並插入末尾操做
internal = setInterval(() => {
const firstEle = initArr[0];
initArr.shift();
initArr.push(firstEle);
this.setData({
lampData: initArr,
showItem: true
});
}, 2000);
}
}
}
});
 
引用該組件wxml文件代碼片斷:
<view class="horse-run-lamp">
<horserunlamp lampData="{{pageData.success_users}}"/>
</view>
 
引用該組件json文件代碼片斷:
{
"navigationBarTitleText": "test頁面",
"usingComponents": {
"horserunlamp": "../../../../components/HoseRunLamp/index"
}
}
相關文章
相關標籤/搜索