vue实现卡片重叠轮播
Vue实现卡片重叠轮播
核心思路
利用CSS的transform和z-index属性控制卡片层叠效果,结合Vue的动态数据绑定和过渡动画实现轮播交互。通过计算卡片位置和透明度实现视觉上的重叠效果。
实现步骤
1. 数据结构设计
data() {
return {
cards: [
{ id: 1, title: 'Card 1' },
{ id: 2, title: 'Card 2' },
{ id: 3, title: 'Card 3' }
],
currentIndex: 0
}
}
2. 模板结构
<div class="carousel-container">
<div
v-for="(card, index) in cards"
:key="card.id"
class="card"
:style="getCardStyle(index)"
@click="handleCardClick(index)"
>
{{ card.title }}
</div>
</div>
3. 样式设计
.carousel-container {
position: relative;
width: 300px;
height: 200px;
perspective: 1000px;
}
.card {
position: absolute;
width: 80%;
height: 80%;
background: #fff;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
transition: all 0.5s ease;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
4. 计算卡片位置
methods: {
getCardStyle(index) {
const diff = index - this.currentIndex;
const scale = 1 - Math.abs(diff) * 0.1;
const zIndex = this.cards.length - Math.abs(diff);
return {
transform: `
translateX(${diff * 30}px)
scale(${scale})
`,
zIndex,
opacity: 1 - Math.abs(diff) * 0.3
}
}
}
5. 轮播控制
methods: {
handleCardClick(index) {
this.currentIndex = index;
},
autoPlay() {
setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.cards.length;
}, 3000);
}
},
mounted() {
this.autoPlay();
}
高级优化
添加3D旋转效果
修改CSS样式增加transform-style: preserve-3d和旋转效果:
.card {
transform-style: preserve-3d;
transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}
触摸滑动支持
添加touchstart、touchmove和touchend事件处理实现滑动切换:
data() {
return {
touchStartX: 0
}
},
methods: {
handleTouchStart(e) {
this.touchStartX = e.touches[0].clientX;
},
handleTouchEnd(e) {
const touchEndX = e.changedTouches[0].clientX;
const diff = touchEndX - this.touchStartX;
if (Math.abs(diff) > 50) {
if (diff > 0) {
this.currentIndex = Math.max(0, this.currentIndex - 1);
} else {
this.currentIndex = Math.min(this.cards.length - 1, this.currentIndex + 1);
}
}
}
}
注意事项
- 卡片数量建议控制在3-5个,过多会影响性能
- 移动端需考虑触摸事件兼容性
- 过渡动画使用CSS硬件加速属性优化性能
- 轮播间隔时间根据实际需求调整







