You need to enable JavaScript to run this app. 如何在Swiper JS中同时实现进度条与分式分页功能?
优惠活动
大模型
产品
解决方案
定价
更多

如何在Swiper JS中同时实现进度条与分式分页功能?

Swiper同时启用进度条与分式分页的实现方案

效果参考

1. 组件引入

Swiper 7及以上版本需要显式引入并注册Progress和Pagination两个组件,同时引入对应样式:

// 核心包引入
import Swiper from 'swiper'
// 组件引入
import { Pagination, Progress } from 'swiper/modules'
// 样式引入
import 'swiper/css'
import 'swiper/css/pagination'
import 'swiper/css/progress'

如果是直接用CDN引入的完整版Swiper,不需要单独注册组件,可跳过这一步。

2. HTML结构配置

按照如下结构定义Swiper容器,同时留出进度条和分式分页的挂载节点:

<div class="mySwiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide">幻灯片1</div>
    <div class="swiper-slide">幻灯片2</div>
    <div class="swiper-slide">幻灯片3</div>
    <div class="swiper-slide">幻灯片4</div>
  </div>
  <!-- 进度条挂载节点 -->
  <div class="swiper-progressbar"></div>
  <!-- 分式分页挂载节点 -->
  <div class="swiper-pagination"></div>
</div>

3. Swiper初始化配置

初始化时同时配置两个组件的参数,注意分页类型指定为fraction:

const swiper = new Swiper('.mySwiper', {
  // 注册组件(CDN引入时可省略)
  modules: [Pagination, Progress],
  // 分式分页配置
  pagination: {
    el: '.swiper-pagination',
    type: 'fraction'
  },
  // 进度条配置
  progress: {
    el: '.swiper-progressbar'
  },
  // 其他自定义配置
  slidesPerView: 1,
  spaceBetween: 20,
  loop: false
})

4. 基础样式补充

需要给进度条添加基础样式,否则默认不显示:

.swiper-progressbar {
  width: 100%;
  height: 4px;
  background-color: #e5e5e5;
  margin: 12px 0;
  border-radius: 2px;
  overflow: hidden;
}
.swiper-progressbar .swiper-progressbar-fill {
  height: 100%;
  background-color: #007aff;
  transition: width 0.3s ease;
}

常见冲突排查

  • 不要在配置中重复声明pagination或progress字段,避免后声明的配置覆盖前者
  • 两个组件的el字段对应的DOM类名不要写错,不要共用同一个挂载节点
  • 如果开启了loop模式,要确保分页和进度条的更新逻辑和loop配置匹配,避免计数错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 23:54:02