uniapp动画的爬坑之路---循环动画不生效

看了官方文档发现没有动画循环这个功能,所有要我们自己写个定时器去重复执行,但今天在做跑马灯的时候发现,获取的元素的宽度后,无法循环播放,后来发现,不能输入固定值,只能输入随机数才可以实现无线循环动画效果

<template>
	<view class="home">
		<view class="notice-box">
					<view class="notice-txt" id="notice-txt" :animation="marquee">{{ notice }}</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			marquee: {} ,//跑马灯效果
			animation : {},
			noticeWidth : 0, // 公告宽度
		};
	},
	methods: {
	
		startAni(){
			const that = this;
            //这里输入固定值的话  循环动画就没执行了  所以加上一个随机数就可以了
			that.animation.translateX(-that.noticeWidth + Number(Math.random() * 10)).step({
				duration: 20000
			});
			that.animation.translateX(0).step({
				duration: 0
			})
			that.marquee = that.animation.export();
			
		},
		loopAni(){
			const that = this;
			let timer = null;
			clearInterval(timer);
			timer = setInterval(()=>{
				
				that.startAni();
			},20010); //这个的时间比动画的时间多一点点  防止动画没做完又执行了
		}
	},
	onShow() {
		const that = this;
		/* 创建的动画 */
		var animation = uni.createAnimation({
			duration: 20000,
			timingFunction: 'linear'
		});
		that.animation = animation;
        //模仿ajax请求
        setTimeout(()=>{
			/* 获取公告宽度 */
			let info = uni.createSelectorQuery().select('.notice-txt');
			info.boundingClientRect(function(cdata) {
			that.noticeWidth = cdata.width; // 获取元素宽度
			that.startAni();
			that.loopAni();
		  }).exec();
		},1000);
	}
};
</script>

<style scoped lang="scss">
.notice-box {
	white-space: nowrap;
	float: left;
	position: absolute;
	top: 0;
	left: 130rpx;
	width: calc(100vw - 200rpx);
	height: 38rpx;
	overflow: hidden;
	.notice-txt{
		position: absolute;
		top: 0;
		left: 0;
		width: auto;
	}
}
</style>
发布了29 篇原创文章 · 获赞 4 · 访问量 3600

猜你喜欢

转载自blog.csdn.net/qq_37564189/article/details/103438094