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

Swiper.js如何实现仅禁止第一个slide向左滑动?

实现方案

基础实现(适用于非循环模式)

通过监听Swiper的滑动切换事件,动态修改allowSlidePrev配置即可实现需求,代码示例如下:

const swiper = new Swiper('.swiper', {
  // 此处保留你原有的所有Swiper配置,比如pagination、navigation等
  on: {
    // 初始化时判断当前位置
    init: function () {
      this.allowSlidePrev = this.activeIndex !== 0;
    },
    // 每次滑动结束后更新配置
    slideChange: function () {
      this.allowSlidePrev = this.activeIndex !== 0;
    }
  }
});

循环模式兼容(开启loop: true时使用)

如果开启了循环滚动模式,需要使用真实索引realIndex替代默认的activeIndex,避免克隆节点干扰判断:

const swiper = new Swiper('.swiper', {
  loop: true,
  // 其他原有配置
  on: {
    init: function () {
      this.allowSlidePrev = this.realIndex !== 0;
    },
    slideChange: function () {
      this.allowSlidePrev = this.realIndex !== 0;
    }
  }
});

框架组件适配(以React为例)

如果使用的是Swiper的框架封装组件,可以通过状态绑定实现同样效果:

import { useState } from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import 'swiper/css';

export default function MySwiper() {
  const [allowPrev, setAllowPrev] = useState(false);

  return (
    <Swiper
      allowSlidePrev={allowPrev}
      onSlideChange={(swiper) => setAllowPrev(swiper.activeIndex !== 0)}
      // 其他配置项
    >
      <SwiperSlide>Slide 1</SwiperSlide>
      <SwiperSlide>Slide 2</SwiperSlide>
      <SwiperSlide>Slide 3</SwiperSlide>
      <SwiperSlide>Slide 4</SwiperSlide>
    </Swiper>
  );
}

以上方案不限制slide总数量,只要处于第一个slide位置就会自动禁止向左滑动,其他位置都可以正常左滑回退。

内容的提问来源于stack exchange,提问作者김대일

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:06:02