uniapp swiper 如何实现堆叠卡片效果

在uniapp中使用swiper组件时,如何实现类似堆叠卡片的滑动效果?我希望卡片能够层叠展示,滑动时有堆叠的视觉层次感,类似iOS的卡片堆叠样式。目前尝试过调整z-index和transform样式,但滑动过渡效果不理想。请问有没有成熟的实现方案或组件推荐?需要兼容H5和小程序平台。

2 回复

使用swiper的previous-marginnext-margin属性,配合circular循环模式。调整间距露出前后卡片,再通过样式设置圆角阴影即可实现堆叠效果。


在 UniApp 中,可以使用 swiper 组件结合 CSS 样式实现堆叠卡片效果。以下是实现步骤和示例代码:

实现思路

  1. 使用 swiper 组件作为容器,设置 circulartrue 实现循环滑动。
  2. 通过 CSS 的 transform 属性调整非活动卡片的位置和缩放,形成堆叠效果。
  3. 利用 swipercurrent 属性和 change 事件动态更新样式。

示例代码

<template>
  <view class="container">
    <swiper
      class="swiper"
      :current="current"
      :circular="true"
      @change="onSwiperChange"
    >
      <swiper-item v-for="(item, index) in list" :key="index">
        <view class="card" :class="{ active: current === index }">
          <text>{{ item }}</text>
        </view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script>
export default {
  data() {
    return {
      current: 0,
      list: ['卡片1', '卡片2', '卡片3', '卡片4']
    }
  },
  methods: {
    onSwiperChange(e) {
      this.current = e.detail.current
    }
  }
}
</script>

<style scoped>
.swiper {
  height: 400rpx;
}

.card {
  position: absolute;
  width: 80%;
  height: 300rpx;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  left: 10%;
  top: 50rpx;
}

/* 非活动卡片样式 */
.card:not(.active) {
  transform: scale(0.85) translateY(40rpx);
  opacity: 0.6;
  z-index: 0;
}

/* 活动卡片样式 */
.card.active {
  transform: scale(1);
  opacity: 1;
  z-index: 1;
}
</style>

关键点说明

  • current 绑定:通过 current 属性控制当前显示的卡片。
  • change 事件:滑动时更新 current 值,触发样式变化。
  • CSS 变换:非活动卡片通过 scaletranslateY 缩小并下移,形成堆叠视觉。
  • 层级管理:使用 z-index 确保活动卡片在最上层。

调整建议

  • 可根据需求修改 scale 值、偏移距离或阴影效果。
  • 支持动态数据绑定,list 数组可替换为实际数据源。

此方法简洁高效,适用于常见堆叠卡片场景。

回到顶部