您的当前位置:首页正文

vue实现无缝滚动的示例详解

2024-11-03 来源:个人技术集锦

vue非组件实现列表的无缝滚动问题(小编能力有限,如有更好方法还请大佬指点一二)

*原理:首先循环两遍数组,当容器滚去第一个数组高度的时候,第二个数组刚好填满容器,这时候将滚去高度设置为0则可以实现无缝滚动。

*简易原理图如下

话不多说直接上代码:

1.采用js的方法实现

<template>
	<div>
		<div class="box">
			<div v-for="item in 2" class="item-box" :style="{transform:'translate(0,'+scrollTop+'px)'}">
				<div class="item" v-for="i in 9">{{i}}</div>
			</div>
		</div>
	</div>
</template>
<script>
	export default {
		data() {
			return {
				scrollTop: 0,
			}
		},
		onLoad() {
			this.roll()
		},
		methods: {
			roll() {
				if (this.scrollTop == -300) {
					this.scrollTop = 0
				}
				this.scrollTop -= 1;
				setTimeout(() => {
					this.roll()
				}, 10)
			},
		}
	}
</script>
<style>
	.box {
		width: 320px;
		height: 300px;
		background-color: pink;
		overflow: hidden;
	}
	.box .item-box {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-wrap: wrap;
	}
	.box .item-box .item {
		width: 29%;
		height: 29%;
		margin: 1%;
		background-color: paleturquoise;
		display: flex;
		align-items: center;
		justify-content: center;
		font-weight: 700;
	}
</style>

2.css动画实现

<template>
	<div>
		<div class="box">
			<div v-for="item in 2" class="item-box">
				<div class="item" v-for="i in 9">{{i}}</div>
			</div>
		</div>
	</div>
</template>
<script>
	export default {
		data() {
			return {}
		},
		methods: {
		}
	}
</script>
<style>
	.box {
		width: 320px;
		height: 300px;
		background-color: pink;
		overflow: hidden;
	}
	.box .item-box {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-wrap: wrap;
		animation: roll 5s linear infinite;
	}
	.box .item-box .item {
		width: 29%;
		height: 29%;
		margin: 1%;
		background-color: paleturquoise;
		display: flex;
		align-items: center;
		justify-content: center;
		font-weight: 700;
	}
	@keyframes roll {
		0% {
			transform: translate(0, 0px);
		}
		20% {
			transform: translate(0, -60px);
		}
		40% {
			transform: translate(0, -120px);
		}
		60% {
			transform: translate(0, -180px);
		}
		80% {
			transform: translate(0, -240px);
		}
		100% {
			transform: translate(0, -300px);
		}
	}
</style>
您可能感兴趣的文章:
显示全文