实现带上下页切换按钮的图片modal,点击获取图片索引切换对应src
实现方案
现有代码问题说明
- 原for循环中的遍历变量
i未用let声明,存在闭包问题,点击事件触发时i已经是遍历完成的最终值,无法拿到对应图片的正确索引 - 每次点击图片都会往modal中新增img节点,多次点击会出现节点堆积
- 没有全局变量存储当前选中图片的索引,也没有绑定切换逻辑的触发入口
HTML调整
先给modal补充关闭、上一张、下一张按钮,你可以自行写CSS将按钮定位到合适位置:
<div class="modal"> <span class="modal-close">×</span> <span class="modal-prev">←</span> <span class="modal-next">→</span> </div>
完整JS代码
const galleryImages = document.querySelectorAll(".img-grid img") const modal = document.querySelector(".modal") const modalClose = document.querySelector(".modal-close") const modalPrev = document.querySelector(".modal-prev") const modalNext = document.querySelector(".modal-next") // 存储当前展示图片的索引 let currentIndex = 0 // 提前创建modal内的img节点,避免重复新建 const modalImg = document.createElement("img") modalImg.classList.add("createdImg") modal.appendChild(modalImg) // 提取所有图片的src存为数组,切换时直接通过索引取值 const imgSrcList = Array.from(galleryImages).map(img => img.src) // 给每个图片绑定点击事件,用forEach可以直接拿到对应索引 galleryImages.forEach((img, index) => { img.addEventListener("click", () => { currentIndex = index modalImg.src = imgSrcList[currentIndex] modal.classList.add("active") document.body.style.overflow = "hidden" }) }) // 关闭modal逻辑 modalClose.addEventListener("click", () => { modal.classList.remove("active") document.body.style.overflow = "auto" }) // 上一张切换逻辑,取余实现循环切换 modalPrev.addEventListener("click", () => { currentIndex = (currentIndex - 1 + imgSrcList.length) % imgSrcList.length modalImg.src = imgSrcList[currentIndex] }) // 下一张切换逻辑 modalNext.addEventListener("click", () => { currentIndex = (currentIndex + 1) % imgSrcList.length modalImg.src = imgSrcList[currentIndex] }) // 可选:点击modal空白区域关闭 modal.addEventListener("click", (e) => { if(e.target === modal) { modal.classList.remove("active") document.body.style.overflow = "auto" } })
核心逻辑说明
- 通过
forEach遍历图片节点可以直接拿到每个节点对应的索引,不需要额外处理闭包问题 - 提前存储所有图片的src到数组,切换时直接通过索引取值即可,不需要再遍历DOM节点
- 索引增减时通过取余处理,实现图片列表的循环切换,不会出现索引越界报错
内容的提问来源于stack exchange,提问作者freeCoder
相关产品推荐
相关产品推荐

