微信小程序动态数据跑马灯组件编写

开发必备:熟悉微信小程序组件开发

开发思路:如果只有一条数据,直接用css3关键帧动画;如果有多条数据,则在当前动画运动到一定时间的时候,将其数据替换掉,使之在视觉效果上有一个从下到上播放的状态。数组循环播放的状态是通过将当前播放元素置换到末尾实现,即通过数组元素删除插入方法将整个数组元素串成一个闭环。

本例是将跑马灯作为一个公共组件开发的,故代码展示为组件形式

目标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"
}
}
posted @ 2019-01-09 16:41  南韵  阅读(1210)  评论(0编辑  收藏  举报