用 display: none 实现轮播最简单可靠:所有图片平铺在 .carousel 内,设固定宽高和容器高度;js 仅需 clear、计算索引、统一设 none 后单设 block;必须悬停暂停并每次切换前清定时器。

直接用 display: none 切换图片是最简单、最不容易出错的起点——不需要 transform、不用 flex 排列、不碰 animation,三步就能跑起来。
结构就用 <div> 套 <code><img>,别嵌套多余标签
把所有图片平铺放在一个 <div class="carousel"> 里,每张图用独立的 <code><img> 标签,带 alt 和固定宽高(比如 width="600" style="max-width:90%"):
<div class="carousel"> @@##@@ @@##@@ @@##@@ </div>
常见错误是塞进 <ul><li></ul> 或 <picture></picture>,初学反而增加选择器复杂度和加载逻辑;也别写 src="a.jpg,b.jpg"——src 只认单个 URL,这样写图根本不会显示。
- 容器必须设固定高度(如
height: 400px),否则display切换会引发重排,页面跳动 - 所有
<img src="1.jpg" alt="第一张" style="max-width:90%" style="max-width:90%">默认加style="display: none;",第一张额外加style="display: block;" - 不要用
visibility: hidden或opacity: 0替代——前者占位影响容器高度,后者仍响应鼠标事件
JS 控制只做两件事:clearInterval + showImage(index)
核心逻辑就是:清掉旧定时器 → 算出下一张索引 → 把所有 <img src="2.jpg" alt="第二张" style="max-width:90%" style="max-width:90%"> 设 display: none → 把目标那张设 display: block。别在 setInterval 里直接写 DOM 操作,先封装函数:
let timer = null;
const images = document.querySelectorAll('.carousel img');
const showImage = (index) => {
images.forEach((img, i) => img.style.display = i === index ? 'block' : 'none');
};
const next = () => {
const currentIndex = Array.from(images).findIndex(img => img.style.display === 'block');
const nextIndex = (currentIndex + 1) % images.length;
showImage(nextIndex);
};
// 启动自动轮播
const start = () => {
clearInterval(timer);
timer = setInterval(next, 3000);
};
- 每次调用
next()前必须clearInterval(timer),否则手动点击后定时器还在跑,导致图片乱切 - 索引用
% images.length实现循环,不用额外判断边界 - 别用
setTimeout递归模拟轮播——容易堆栈溢出,且无法统一清理
悬停暂停必须配 mouseenter/mouseleave,不是可选项
用户鼠标移上去还在切图,是反直觉体验。暂停逻辑不是“点按钮才停”,而是“有交互就停”:
const carousel = document.querySelector('.carousel');
carousel.addEventListener('mouseenter', () => clearInterval(timer));
carousel.addEventListener('mouseleave', start);
-
mouseleave触发start()是为了恢复自动播放,不是重新setInterval——start()内部已含clearInterval,避免多个定时器并发 - 移动端没有 hover,但
mouseenter不会报错,可直接共用;若需 touch 支持,再加touchstart即可 - 左右箭头按钮的
click事件里也要调用clearInterval(timer),否则刚点完“下一张”,0.5 秒后又自动切
真正难的不是让图动起来,而是让动得稳、停得准、切得不冲突——所有坑都集中在定时器管理和显隐顺序上。只要守住「每次切换前先清定时器、先全设 none、再单设 block」这三条,哪怕只有 5 行 JS,也能撑住生产环境首屏轮播。












