卡片轮播(多张并排)
卡片轮播:一次显示多张卡片(如一屏 3 张),左右切换时移动一格。与基础轮播的区别只是位移单位从“整屏”变成“卡片宽”,轨道仍是一个 flex 容器。
响应式配合:用 CSS 变量 --w 定义卡片宽度,JS 位移 = -index * 卡片宽;想一次移动多张就把步长乘上数量。Swiper 等库核心也是这个结构。
- 轨道所有卡片 flex 排列,视口宽度 = 卡片宽 × 可见数
- JS 位移 -index × 卡片宽度(可用 CSS 变量同步)
- 边界处理:到头不让继续点(或克隆实现无缝)
HTML
<style> #cardsl { max-width: 480px; margin: 20px auto; } #cardsl .vp { overflow: hidden; } #cardsl .track { display: flex; gap: 12px; transition: transform .4s ease; } #cardsl .card { min-width: calc((100% - 24px) / 3); height: 110px; border-radius: 10px; color: #fff; display: flex; align-items: center; justify-content: center; font-size: 16px; } #cardsl .c1 { background: #4a9eff; } #cardsl .c2 { background: #f778ba; } #cardsl .c3 { background: #57ab5a; } #cardsl .c4 { background: #e78a3e; } #cardsl .c5 { background: #a371f7; } #cardsl .c6 { background: #39c5cf; } #cardsl .ops { text-align: center; margin-top: 12px; } #cardsl .ops button { padding: 6px 16px; margin: 0 6px; border: none; border-radius: 8px; background: #f0e6ff; cursor: pointer; } </style> <div id="cardsl"> <div class="vp"><div class="track"> <div class="card c1">卡片1</div><div class="card c2">卡片2</div> <div class="card c3">卡片3</div><div class="card c4">卡片4</div> <div class="card c5">卡片5</div><div class="card c6">卡片6</div> </div></div> <div class="ops"><button id="cp">‹ 上一组</button><button id="cn">下一组 ›</button></div> </div> <script> var track = document.querySelector('#cardsl .track'); var total = track.children.length; // 6 张 var vis = 3, stepIdx = 0; // 一次移 1 张 function go(n) { var max = total - vis; // 最多能移到的格数 stepIdx = Math.max(0, Math.min(n, max)); // 卡片宽 = (100% - 24px) / 3,含右侧 gap 12px,一次位移 = 卡片宽 + gap track.style.transform = 'translateX(calc(-1 * ' + stepIdx + ' * ((100% - 24px) / 3 + 12px)))'; } document.getElementById('cp').addEventListener('click', function () { go(stepIdx - 1); }); document.getElementById('cn').addEventListener('click', function () { go(stepIdx + 1); }); </script>
本节要点卡片轮播 = 位移单位变成卡片宽(calc 处理 gap);边界用 max-min clamp。




