开启loop模式后如何获取SwiperJS真实activeSlide索引?
SwiperJS Loop模式下activeIndex索引异常的解决办法
问题原因
当Swiper开启loop模式时,它会自动在真实幻灯片的首尾复制若干份幻灯片(默认1份)来实现无缝循环滑动。此时直接获取activeIndex得到的是包含复制幻灯片在内的全局索引,而非你实际定义的真实幻灯片索引,这就是滑动到末尾时出现异常索引值的核心原因。
解决办法
使用Swiper提供的realIndex属性替代activeIndex,realIndex会返回当前活跃幻灯片对应的真实原始索引,完全不受Loop模式复制的幻灯片影响。
修改后的代码
const currentProductTitle = document.getElementById( "current-product-title", ); const swiperProducts = new Swiper(".best-product-swiper__container", { direction: "horizontal", loop: true, // 注意这里要开启loop模式,你原代码里写的是false navigation: { nextEl: ".best-product-swiper__next-btn", prevEl: ".best-product-swiper__prev-btn", }, speed: 600, }); swiperProducts.on("slideChange", function () { console.log(swiperProducts.realIndex); // 替换为realIndex switch (swiperProducts.realIndex) { case 0: currentProductTitle.innerHTML = "DOG LEASH"; break; case 1: if (window.matchMedia("(max-width: 835px)").matches) { currentProductTitle.innerHTML = "DOG <br> BED"; } else { currentProductTitle.innerHTML = "DOG BED"; } break; case 2: currentProductTitle.innerHTML = "GPS COLLAR"; break; case 3: currentProductTitle.innerHTML = "DOG HARNESS"; break; case 4: currentProductTitle.innerHTML = "HAIR BRUSH"; break; case 5: currentProductTitle.innerHTML = "DOG LEASH"; break; } });
额外注意点
- 如果你自定义了
loopedSlides参数(设置复制的幻灯片数量),realIndex依然能正确返回真实索引,无需额外调整。 - 确保你的Swiper版本支持
realIndex属性,目前主流的Swiper 6+版本都已支持该属性。
内容的提问来源于stack exchange,提问作者Oleksandr Rostiahai
相关产品推荐
相关产品推荐

