vue实现字体垂直轮播
实现思路
垂直轮播效果可以通过动态改变字体容器的 transform 或 margin-top 属性来实现。使用 Vue 的过渡动画和定时器控制轮播节奏。
基本结构
创建包含轮播内容的容器,使用 v-for 渲染列表,通过 CSS 控制垂直排列和隐藏溢出部分。
<template>
<div class="vertical-carousel">
<div class="carousel-container" :style="{ transform: `translateY(${offset}px)` }">
<div v-for="(item, index) in items" :key="index" class="carousel-item">
{{ item.text }}
</div>
</div>
</div>
</template>
数据与样式
定义轮播数据和基础样式,确保容器高度固定且溢出隐藏。
<script>
export default {
data() {
return {
items: [
{ text: "第一项内容" },
{ text: "第二项内容" },
{ text: "第三项内容" }
],
currentIndex: 0,
offset: 0,
itemHeight: 40 // 根据实际样式调整
};
}
};
</script>
<style>
.vertical-carousel {
height: 40px;
overflow: hidden;
}
.carousel-container {
transition: transform 0.5s ease;
}
.carousel-item {
height: 40px;
line-height: 40px;
}
</style>
自动轮播逻辑
通过 setInterval 控制轮播,更新 offset 实现滚动效果。注意组件销毁时清除定时器。
<script>
export default {
mounted() {
this.startCarousel();
},
beforeDestroy() {
clearInterval(this.timer);
},
methods: {
startCarousel() {
this.timer = setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.items.length;
this.offset = -this.currentIndex * this.itemHeight;
}, 2000);
}
}
};
</script>
平滑过渡优化
添加过渡效果,确保轮播时内容平滑移动。可通过 CSS 的 transition 属性实现。
.carousel-container {
transition: transform 0.5s ease;
}
无限循环处理
克隆首项数据至末尾,实现无缝循环。需在滚动到末尾时重置位置。
<script>
export default {
data() {
return {
items: [
{ text: "第一项内容" },
{ text: "第二项内容" },
{ text: "第三项内容" },
{ text: "第一项内容" } // 克隆首项
],
itemCount: 3 // 实际项数
};
},
methods: {
startCarousel() {
this.timer = setInterval(() => {
this.currentIndex++;
if (this.currentIndex >= this.itemCount) {
setTimeout(() => {
this.currentIndex = 0;
this.offset = 0;
}, 500); // 过渡完成后重置
}
this.offset = -this.currentIndex * this.itemHeight;
}, 2000);
}
}
};
</script>
手势支持(可选)
添加 touchstart、touchmove 事件实现手动滑动交互,需计算滑动距离与方向。
<script>
export default {
methods: {
handleTouchStart(e) {
this.startY = e.touches[0].clientY;
},
handleTouchMove(e) {
const currentY = e.touches[0].clientY;
this.deltaY = currentY - this.startY;
this.offset = -this.currentIndex * this.itemHeight + this.deltaY;
},
handleTouchEnd() {
if (Math.abs(this.deltaY) > this.itemHeight / 2) {
this.currentIndex += this.deltaY > 0 ? -1 : 1;
}
this.offset = -this.currentIndex * this.itemHeight;
}
}
};
</script>
响应式调整
监听容器高度变化,动态计算 itemHeight。可使用 ResizeObserver 或窗口大小事件。
<script>
export default {
mounted() {
this.updateItemHeight();
window.addEventListener('resize', this.updateItemHeight);
},
methods: {
updateItemHeight() {
this.itemHeight = this.$el.clientHeight;
}
}
};
</script>
以上方法组合可实现一个完整的垂直字体轮播效果,支持自动播放、平滑过渡和手动交互。







