首页 / 中文教程 / 教程

为 Bricks 嵌套轮播添加进度条

本教程教你如何给 Brickshttps://brickslabs.com/go/bricks 的嵌套轮播(nested slider)元素添加进度条,效果参考 SplideJS 官网的轮播进度示例https://spl…

Ray Chan·2026-08-12·约 2 分钟

本教程教你如何给 Bricks 的嵌套轮播(nested slider)元素添加进度条,效果参考 SplideJS 官网的轮播进度示例。与其他库不同,SplideJS 显示进度条需要自己写一点自定义 JavaScript。

目录

DOM 结构

在 Bricks 里搭出下面的结构,类名按下图分配

注意进度条被包在一个块(Block)元素里(这个块不需要特定类名就能工作)。用这个包裹层给进度条设置背景色

接下来处理进度条 div 本身。

首先,把宽度设为 0px,并设置想要的高度(示例用 4px):

然后设置进度条的背景色

最后加一个顺滑的过渡(transition)

JavaScript

把下面这段代码加载到子主题里,或用代码片段插件加载:

document.addEventListener('DOMContentLoaded', () => {

   // Query all the grid sliders on the page
   const sliders = document.querySelectorAll('.sliders-progress-wrapper');

   // Stop the function if there is no sync slider
   if (sliders.length < 1) return;

   // Debounce function
   const debounce = (fn, threshold) => {
      var timeout;
      threshold = threshold || 200;
      return function debounced() {
         clearTimeout(timeout);
         var args = arguments;
         var _this = this;

         function delayed() {
            fn.apply(_this, args);
         }
         timeout = setTimeout(delayed, threshold);
      };
   };

   // Init function
   const init = (bar, sliderId) => {

      // get the slider instance
      const instance = bricksData.splideInstances[sliderId];

      // Destroy the instance
      instance.destroy(true);

      // Change the width of the progress bar when mounted and when the slider moves
      instance.on('mounted move', function () {
         const end = instance.Components.Controller.getEnd() + 1;
         const rate = Math.min((instance.index + 1) / end, 1);
         bar.style.width = String(100 * rate) + '%';
      });

      // Remount the instance
      instance.mount();

   };
   // Loop into each wrapper
   sliders.forEach(slider => {

      // Query the progress bar element
      const bar = slider.querySelector('.slider-progress-bar');

      // Query the nested slider element
      const mainSlider = slider.querySelector('.slider-main');

      // Get the instance ID generated by Bricks
      const sliderId = mainSlider.dataset.scriptId;

      // Run the function on load
      setTimeout(() => {
         init(bar, sliderId);
      }, 0);

      // Rerun the function on resize because bricks reinit the sliders on each resize event
      window.addEventListener("resize", debounce(() => {
         init(bar, sliderId);
      }, 300));

   });
});

脚本逻辑:每个 .sliders-progress-wrapper 包裹层里找到进度条(.slider-progress-bar)和轮播本体(.slider-main),通过 mainSlider.dataset.scriptId 拿到 Bricks 生成的实例 ID,销毁后用 instance.on('mounted move', ...) 监听挂载与滑动事件,按 (当前索引 + 1) / 总页数 计算进度百分比并写入进度条宽度;resize 时用 300ms 防抖重新执行(因为 Bricks 每次 resize 都会重初始化轮播)。

一切正常的话,前端就能看到进度条跟随轮播滑动了:

参考资料

需要帮忙?

用 Bricks 建站?我接客户项目。

从快速营销站到完整的 Bricks 建站,再到从 Elementor 迁移——我都做过。本站每篇教程都来自真实项目经验。告诉我你的需求,一个工作日内回复。

  • Bricks 建站与改版
  • Elementor / Divi → Bricks 迁移
  • Bricks → Astro / headless 性能升级
  • 速度优化,PageSpeed 95+ 目标