纯css轮播可用@keyframes+radio模拟切换,但无交互;swiper需满足容器宽度、结构嵌套、dom就绪三约束,注意touch-action冲突和disableoninteraction默认值。

用 HTML + CSS 实现基础轮播,不依赖 JS 就能跑起来
纯 HTML/CSS 能做轮播,但仅限“单次自动播放+无交互”场景。核心靠 @keyframes + animation 控制位移,用 input[type="radio"] 模拟手动切换(需配合 :checked 和兄弟选择器)。好处是零 JS、加载快;坏处是无法暂停、不能响应式缩放、iOS Safari 对 animation-timing-function 的 steps() 支持不稳定。
- 每个评价项用
div包裹,统一设为display: inline-block,父容器white-space: nowrap - 用
label关联input[type="radio"],点击 label 切换选中状态,再用input:checked ~ .carousel-item控制显隐 - 动画时间要和轮播间隔对齐,比如 5s 切一张,
animation-duration就设20s(4 张 × 5s),用steps(4)实现帧跳变 - 别用
transform: translateX()做位移——部分旧版安卓 WebView 会闪屏,改用margin-left更稳
Swiper 初始化失败?检查这三处硬性约束
Swiper 不是扔进页面就能动的库。最常见报错是 Cannot read property 'length' of undefined,本质是容器结构没满足它的 DOM 预期。
- 外层容器必须有明确宽度,不能是
width: auto或未设置;若父级是 flex 项,加flex-shrink: 0 - 轮播内容必须包在
div.swiper-wrapper里,每张卡片是div.swiper-slide——少一层 wrapper,swiper.slideTo()直接失效 - 初始化前确保 DOM 已就绪,
document.addEventListener('DOMContentLoaded', ...)比window.onload更安全,后者等资源加载完才触发,可能晚于 Swiper 自检
移动端手势失效:不是 CSS 问题,是 touch-action 搞的鬼
滑不动、卡顿、手指一碰就跳到下一页——90% 是 touch-action 属性冲突。Swiper 默认设 touch-action: pan-y(只允许竖向拖拽),但如果你给轮播区域或其祖先加了 touch-action: none 或 touch-action: manipulation,手势事件就被浏览器截断了。
- 检查所有父级元素的 computed style,重点搜
touch-action,把非必要的删掉 - 如果用了
position: fixed容器,iOS 上需额外加-webkit-overflow-scrolling: touch启用手势惯性 - 避免在
.swiper-slide内嵌套iframe或video,它们自带 touch-action 行为,会干扰 Swiper 的 touchstart 监听
autoplay 开了却停不下来?优先查 disableOnInteraction 默认值
Swiper v6+ 默认开启 disableOnInteraction: true,意思是用户手动滑一次,autoplay 就永久关闭。这不是 bug,是设计选择——但很多人不知道它存在,以为配置写错了。
立即学习“前端免费学习笔记(深入)”;
- 想保持自动播放,初始化时显式写
disableOnInteraction: false - 如果要用「用户操作后暂停 3 秒再继续」,得自己监听
slideChangeTransitionStart事件,调用swiper.autoplay.start() - 注意
delay单位是毫秒,别写成delay: 3(3ms)导致疯狂滚动;常用值是3000或5000 - 服务端渲染(SSR)环境下,
autoplay可能因 window 未定义报错,需在onBeforeInit钩子里判断typeof window !== 'undefined'
轮播最难的从来不是“怎么动起来”,而是“怎么在各种屏幕、各种手势、各种加载时机下,不崩、不卡、不跳”。尤其 touch-action 和 disableOnInteraction 这两个默认开关,不翻源码根本想不到它们在背后掐着脖子。











