You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中用SwiperJS 11.0.4实现中间全图两侧半图循环轮播

React SwiperJS 11.x 实现中间完整、两侧半张的循环轮播

针对你只有两张图片的场景,之前的配置没达到预期,核心问题是循环模式下幻灯片数量不足时的复制逻辑和幻灯片宽度的精准控制,给你一套可直接用的方案:

核心配置要点

  • 显式引入Loop模块(Swiper 11.x 采用模块化拆分,必须手动引入)
  • 配置loopedSlides: 2:因为只有2张幻灯片,告诉Swiper要复制的数量,避免循环时出现空白
  • 用自定义变量控制幻灯片宽度,配合slidesPerView:1.5和centeredSlides:true实现中间完整、两侧半露的效果

完整代码示例

import { Swiper, SwiperSlide } from '@swiper/react';
// 引入基础样式和需要的模块样式
import 'swiper/css';
import 'swiper/css/autoplay';

// 引入所需模块
import { Loop, Autoplay } from 'swiper/modules';

const TwoImageSlider = () => {
  return (
    {/* 外层容器控制整体宽度 */}
    <div style={{ width: '100%', maxWidth: '800px', margin: '0 auto' }}>
      <Swiper
        modules={[Loop, Autoplay]}
        slidesPerView={1.5}
        centeredSlides={true}
        loop={true}
        loopedSlides={2}
        spaceBetween={16} // 幻灯片间距,可根据视觉需求调整
        autoplay={{ 
          delay: 3000, 
          disableOnInteraction: false // 交互后继续自动轮播
        }}
        {/* 自定义幻灯片宽度,这里设为容器的70%,刚好让两侧各露出半张 */}
        style={{ '--swiper-slide-width': '70%' }}
      >
        <SwiperSlide>
          <img 
            src="你的第一张图片地址" 
            alt="幻灯片1" 
            style={{ width: '100%', height: 'auto', objectFit: 'cover' }} 
          />
        </SwiperSlide>
        <SwiperSlide>
          <img 
            src="你的第二张图片地址" 
            alt="幻灯片2" 
            style={{ width: '100%', height: 'auto', objectFit: 'cover' }} 
          />
        </SwiperSlide>
      </Swiper>
    </div>
  );
};

export default TwoImageSlider;

细节调整说明

  1. 幻灯片宽度:如果觉得两侧露出的部分不够/过多,修改--swiper-slide-width的值即可,比如设为65%会让两侧露出更多,75%则露出更少
  2. 间距:spaceBetween控制幻灯片之间的空隙,数值越大,中间幻灯片和两侧的距离越远
  3. 自动轮播:如果不需要自动轮播,去掉Autoplay模块和autoplay配置即可

内容的提问来源于stack exchange,提问作者Ngọc Hòa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 02:34:59