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

如何在React+Swiper.js轮播组件两侧添加白色渐变效果

如何给React+Swiper轮播组件添加两侧白色渐变遮罩效果?

我正在使用React.js和Swiper.js开发轮播组件,当前轮播的配置代码如下:

<Swiper
  spaceBetween={30}
  loop={true}
  slidesPerView={6}
  centeredSlides={true}
  speed={2000}
  navigation={false}
  modules={[Autoplay]}
  grabCursor={true}
  autoplay={{
    delay: 500,
    disableOnInteraction: false
  }}
>
  {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((item) => {
    return (
      <SwiperSlide
        key={item}
        style={{
          width: "100px",
          height: "100px",
          background: "red"
        }}
      >
        <div>{item}</div>
      </SwiperSlide>
    );
  })}
</Swiper>

我想要给这个轮播添加两侧的白色渐变遮罩效果,但之前尝试的CSS方案无效,请问该如何实现?


解决方案:给轮播容器添加外层遮罩容器

由于Swiper内部会生成专属的wrapper等结构元素,直接给Swiper组件加伪元素容易被内部样式干扰。最稳妥的方式是给Swiper套一个外层容器,通过伪元素实现左右渐变遮罩,同时确保遮罩不影响轮播的交互功能。

步骤1:修改JSX结构,添加外层容器

给<Swiper>包裹一个带类名的父容器:

<div className="swiper-gradient-container">
  <Swiper
    // 保留原有配置不变
    spaceBetween={30}
    loop={true}
    slidesPerView={6}
    centeredSlides={true}
    speed={2000}
    navigation={false}
    modules={[Autoplay]}
    grabCursor={true}
    autoplay={{
      delay: 500,
      disableOnInteraction: false
    }}
  >
    {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((item) => {
      return (
        <SwiperSlide
          key={item}
          style={{
            width: "100px",
            height: "100px",
            background: "red"
          }}
        >
          <div>{item}</div>
        </SwiperSlide>
      );
    })}
  </Swiper>
</div>

步骤2:添加CSS样式

通过伪元素::before和::after创建左右渐变遮罩,关键属性说明:

  • pointer-events: none:让遮罩层不拦截鼠标/触摸事件,保证轮播的滑动、点击交互正常
  • z-index: 10:确保遮罩层显示在轮播内容上方
  • linear-gradient:设置从白色到透明的渐变,可根据需求调整渐变宽度和透明度
.swiper-gradient-container {
  position: relative;
  max-width: 100%;
  overflow: hidden;
  /* 若轮播有固定宽度,给容器设置相同宽度即可 */
}

/* 左侧渐变遮罩 */
.swiper-gradient-container::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 80px; /* 遮罩宽度,可自定义 */
  height: 100%;
  background: linear-gradient(to right, #ffffff, rgba(255,255,255,0));
  pointer-events: none;
  z-index: 10;
}

/* 右侧渐变遮罩 */
.swiper-gradient-container::after {
  content: '';
  position: absolute;
  right: 0;
  top: 0;
  width: 80px; /* 遮罩宽度,可自定义 */
  height: 100%;
  background: linear-gradient(to left, #ffffff, rgba(255,255,255,0));
  pointer-events: none;
  z-index: 10;
}

注意事项

  • 如果页面背景不是白色,需将渐变中的#ffffff替换为对应背景色
  • 可通过调整遮罩的width值,控制渐变区域的大小
  • 若轮播容器有固定宽度,给.swiper-gradient-container设置相同宽度即可

内容的提问来源于stack exchange,提问作者SpicyyRiice

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 13:10:14