React中Swiper开启loop模式滚动至数组末尾出现空白间隙问题
Swiper Loop模式滚动末尾出现空白间隙问题
我使用React 18.2.0和Swiper 11.0.5实现垂直轮播,轮播项为0-99的数字数组。开启loop模式后,滚动到数组末尾时会出现空白区域,点击导航按钮再次滚动后间隙消失(右侧、底部均会出现该间隙)。
排查发现,当swiper-wrapper的transform: translate3d值为正数时,间隙就会出现。尝试调整position样式未解决问题,需要实现无间隙的无限循环。
轮播组件代码
<Swiper slidesPerView={5} initialSlide={getInitialSlide(1)} direction={'vertical'} loop={true} modules={[Navigation]} onSlideChange={(slide) => handleSlideChange(slide, 1)} centeredSlides={true} navigation={true} className="swiper--left" > {points.map((item, index) => ( <SwiperSlide key={index}> <div>{item}</div> </SwiperSlide> ))} </Swiper>
左侧Swiper的CSS代码
.swiper { width: 150px; height: 250px; overflow: hidden; overflow-x: auto; position: relative !important; box-sizing: border-box; .swiper-slide { text-align: center; font-size: 30px; color: var(--palette-live-grey-3); height: 50px !important; display: flex; justify-content: center; align-items: center; } .swiper-slide-active { font-size: 40px; color: var(--palette-live-grey-0); } .swiper-slide-prev, .swiper-slide-next { font-size: 35px; color: var(--palette-live-grey-7); } } .swiper--left { position: relative !important; .swiper-button-prev { position: absolute; top: 25%; left: 20px; cursor: pointer; height: 40px; width: 40px; display: flex; justify-content: center; align-items: center; &::before { content: ""; display: inline-block; height: 2px; width: 20px; background-color: var(--palette-live-grey-7); } } .swiper-button-next { position: absolute; bottom: 25%; left: 20px; cursor: pointer; height: 40px; width: 40px; display: flex; justify-content: center; align-items: center; &::before { content: ""; display: inline-block; width: 40px; height: 40px; background: linear-gradient(var(--palette-live-grey-7), var(--palette-live-grey-7)), linear-gradient(var(--palette-live-grey-7), var(--palette-live-grey-7)); background-position: center; background-size: 50% 2px, 2px 50%; background-repeat: no-repeat; } } .swiper-wrapper { width: 50%; position: absolute !important; right: 0px; cursor: pointer; } }
解决方法
- 移除
swiper-wrapper的自定义定位与宽度
自定义的width:50%和position:absolute会破坏Swiper Loop模式的内部布局计算——Loop模式需要依赖默认的wrapper宽度逻辑复制首尾轮播项,自定义定位会导致复制元素位置偏移,出现空白。
删除以下代码:
.swiper-wrapper { width: 50%; position: absolute !important; right: 0px; cursor: pointer; }
若需要轮播项靠右显示,直接调整.swiper-slide的对齐方式即可,比如添加justify-content: flex-end;,或给.swiper设置右侧内边距。
- 清理冗余的横向滚动设置
垂直轮播不需要overflow-x: auto,该属性会干扰横向布局逻辑,移除.swiper中的overflow-x: auto;:
.swiper { /* 删除 overflow-x: auto; */ overflow: hidden; }
- 确保轮播项高度计算准确
给.swiper-slide添加box-sizing: border-box,避免内边距、边框导致高度溢出,破坏布局匹配:
.swiper-slide { box-sizing: border-box; /* 原有样式 */ }
- 手动触发Swiper布局更新
若上述调整后仍有异常,在组件挂载后手动调用Swiper的update方法,强制重新计算布局:
import { useRef, useEffect } from 'react'; const swiperRef = useRef(null); useEffect(() => { swiperRef.current?.update(); }, [points]); // 绑定ref到Swiper组件 <Swiper ref={swiperRef} // 其他属性 > {/* 轮播项 */} </Swiper>
内容的提问来源于stack exchange,提问作者user23354037
相关产品推荐
相关产品推荐

