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

React中如何选中Swiper里.swiper-slide-next的下一个幻灯片

解决方案

方案1:纯CSS选择器实现

直接通过CSS多选择器组合+相邻兄弟选择器,同时选中.swiper-slide-next和它的下一张幻灯片:

:global(.swiper-slide-next, .swiper-slide-next + .swiper-slide) {
  /* 自定义样式示例 */
  opacity: 0.8;
  transform: scale(0.95);
}
  • .swiper-slide-next:匹配Swiper标记的“下一张幻灯片”
  • .swiper-slide-next + .swiper-slide:匹配swiper-slide-next紧接的下一个同级幻灯片元素
  • 逗号分隔实现同时选中两个目标元素,统一应用样式

方案2:Swiper API手动控制类名

如果纯CSS选择器因Swiper DOM结构差异不生效,可通过API手动给目标幻灯片添加自定义类:

1. 修改组件逻辑

export interface SliderProps extends Omit<HTMLProps<HTMLLabelElement>, "label"> {}

const Slider: React.FC<SliderProps> = ({ ...props }) => {
  let swiperInstance: Swiper | null = null;

  const updateHighlightSlides = () => {
    if (!swiperInstance) return;
    // 清除所有已有的高亮类
    document.querySelectorAll('.slide-highlight').forEach(el => el.classList.remove('slide-highlight'));
    
    const nextSlideIndex = swiperInstance.activeIndex + 1;
    // 给下一张幻灯片加类
    if (nextSlideIndex < swiperInstance.slides.length) {
      swiperInstance.slides[nextSlideIndex].classList.add('slide-highlight');
    }
    // 给下下张幻灯片加类
    if (nextSlideIndex + 1 < swiperInstance.slides.length) {
      swiperInstance.slides[nextSlideIndex + 1].classList.add('slide-highlight');
    }
  };

  return (
    <Box sx={{position: 'relative'}}>
      <Swiper
        initialSlide={1}
        className={styles.slider}
        modules={[Navigation]}
        navigation
        onSwiper={(swiper) => {
          swiperInstance = swiper;
          // 初始化时立即执行一次高亮逻辑
          updateHighlightSlides();
        }}
        onSlideChange={updateHighlightSlides}
        breakpoints={{
          640: {
            slidesPerView: 1,
            spaceBetween: 10,
          },
          768: {
            slidesPerView: 2,
            spaceBetween: 40,
          },
          1024: {
            slidesPerView: 4,
            spaceBetween: 10,
          },
        }}
      >
        <SwiperSlide>
          <Card />
        </SwiperSlide>
        <SwiperSlide>
          <Card />
        </SwiperSlide>
        <SwiperSlide>
          <Card />
        </SwiperSlide>
        <SwiperSlide>
          <Card />
        </SwiperSlide>
        <SwiperSlide>
          <Card />
        </SwiperSlide>
        <SwiperSlide>
          <Card />
        </SwiperSlide>
        <SwiperSlide>
          <Card />
        </SwiperSlide>
      </Swiper>
    </Box>
  );
};

export default Slider;

2. 添加对应CSS样式

:global(.slide-highlight) {
  /* 你的自定义样式 */
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:45:20