跑马灯的效果在开发中是很常见的一个需求
例如网站通知、中奖通知、公告、送礼物通知等等
如下代码,使用小程序的动画对象Animation,实现的跑马灯效果:
<button bindtap="start">开始动画</button>
<view class='marquee_container'>
<image class="gift-img" src="{{currentLogs.gift.pic}}" mode="widthFix"></image>
<view class="marquee_main">
<view id="marquee_wrap" class='marquee_text' animation="{{ani}}" bindtransitionend="animationend">
<text>{{currentLogs.from.name}}赠送</text>
<view>LV{{currentLogs.userLevel}}</view>
<text>{{currentLogs.to.name}}</text>
<text>{{currentLogs.gift.name}}</text>
<text>{{'X' + currentLogs.num}}</text>
<view>人气值:{{currentLogs.charm}}</view>
</view>
</view>
</view>
Page({
data: {
ani: "",
length: 0, // 动画内容区宽度
currentLogs: {
charm: 10,
from: {
name: "吴彦祖",
},
gift: {
name: "玫瑰花",
pic: "https://avatar-img.wuhan716.com/voice/gift_rose.png",
},
num: 1,
to: {
name: "彭于晏",
},
userLevel: 4,
},
},
start() {
wx.nextTick(() => {
this.dynamicLength().then(() => {
setTimeout(() => {
this.startAni();
}, 1000);
});
});
},
// 获取内容区域宽
dynamicLength() {
return new Promise((resolve) => {
const that = this;
const query = wx.createSelectorQuery().in(this);
query
.select("#marquee_wrap")
.boundingClientRect((rect) => {
that.setData(
{
length: rect.width,
},
resolve()
);
})
.exec();
});
},
// 开始动画
startAni() {
const { length } = this.data;
const duration = Math.round(length) * 16;
const animation = wx.createAnimation({
duration,
timingFunction: "linear",
delay: 0,
});
animation.translateX(-length).step();
this.setData({
ani: animation.export(),
});
},
// 动画结束时调用
animationend() {
const animation = wx.createAnimation({
duration: 0,
timingFunction: "linear",
delay: 0,
});
animation.translateX(375).step();
this.setData({
ani: animation.export(),
});
},
});
.marquee_container {
position: relative;
top: 50rpx;
left: 0;
width: 100%;
height: 57rpx;
padding-left: 120rpx;
}
.marquee_main{
position: relative;
width: 630rpx;
height: 57rpx;
overflow: hidden;
font-size: 28rpx;
background: cyan;
}
.marquee_text {
height: 57rpx;
position: absolute;
white-space: nowrap;
top: 0;
transform: translateX(750rpx);
display: flex;
align-items: center;
}
.gift-img {
width: 120rpx;
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
}