接上个博客的,文本跑马灯的animate实现
上个版本是根据setinterval定时器修改位置实现动画效果,体验还行,但是太耗资源,如果想体验流畅那么频率就很小,步长也不能太长,但是会很慢,由于频率高,一秒钟执行三四十次,太耗费资源,于是我这边就使用小程序的animate做了另一种实现
主要思路:根据文本的长度设定过渡时间,动画结束后再次滚动即可,直接看代码
wxml
<view class='marquee_container'>
<view id="marquee_wrap" class='marquee_text' animation="{{ani}}" bindtransitionend="animationend" style='{{ orientation }}:{{ marqueeDistance }}px;font-size: {{size}}px;'>
<view class="item" wx:for="{{text}}" wx:for-index="key" wx:for-item="item" wx:key="{{index}}">
{{item.getAwardsUser}}抽中{{item.name}}
</view>
</view>
</view>
js
Component({
/**
* 组件的属性列表
*/
properties: {
text: {
type: Array,
value: [],
observer(newVal, oldVal) {
if(newVal) {
this.dynamicLength()
setTimeout(() => {
this.startAni()
}, 2500);
}
}
}
},
/**
* 组件的初始数据
*/
data: {
orientation: 'left',
windowWidth:750,
length:0,
ani:''
},
created: function() {},
/**
* 组件的方法列表
*/
methods: {
startAni:function(){
let { length } = this.data
// console.log("length", length)
let duration = Math.round(length)*7+5000
var animation = wx.createAnimation({
duration: duration,
timingFunction: 'linear',
delay: 0
});
// animation.translateX(375).step() //有初始化默认位置,这个可以不要
wx.nextTick(()=>{
animation.translateX(-(length+375)).step()
this.setData({
ani: animation.export()
})
})
},
animationend(){
// console.log("animationend...........")
var animation = wx.createAnimation({
duration: 0,
timingFunction: 'linear',
delay: 0
});
animation.translateX(375).step()
this.setData({
ani: animation.export()
})
this.startAni()
},
dynamicLength(){
var _this = this
//选择器
const query = wx.createSelectorQuery().in(this)
query.select('#marquee_wrap').boundingClientRect(function (rect) {
console.log("rect", rect)
_this.setData({
length:rect.width
})
}).exec();
}
}
})
wxss
.marquee_container {
position: relative;
width: 100%;
/* margin-top: 80rpx; */
}
.marquee_text {
position: absolute;
white-space: nowrap;
}
.item{
display: inline;
margin-left:22rpx;
margin-right:22rpx;
padding: 14rpx 40rpx;
line-height: 52rpx;
/* opacity: 0.43; */
/* background: #E1D3C2; */
background: rgba(241, 211, 194, 0.43);
color: #E83C00;
border-radius: 52rpx;
}
.item:first-child{
margin-left:0;
}
.item:last-child{
margin-right:0;
}
整体实现思路和执行顺序就是:每次初始化先获取文本你的实际长度,再进行动画过渡,过渡时间根据你自己的算法来,监听动画执行结束后,直接调用执行动画即可
ps:动画结束触发方法是bindtransitionend,不是transitionend