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

Swiper自定义滑块宽度实现:激活滑块变宽方案咨询

解决方案:Swiper滑块激活时动态调整宽度

核心实现思路

通过Swiper自带的swiper-slide-active类控制slide宽度,配合Swiper的配置项确保布局能正确更新,解决之前调用update方法无效的问题。

具体步骤及代码示例

  1. CSS样式设置
    给slide设置默认宽度,同时通过active类指定激活状态的宽度,务必添加flex-shrink: 0防止slide被自动压缩:
.swiper-slide {
  width: 300px;
  flex-shrink: 0; /* 关键:避免slide被容器压缩 */
  height: 200px;
  background-color: #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: width 0.3s ease; /* 添加平滑过渡效果 */
}

.swiper-slide-active {
  width: 700px;
  background-color: #ccc;
}
  1. Swiper初始化配置
    除了slidesPerView: 'auto',还需要开启watchSlidesProgress: true让Swiper监听slide的尺寸变化,同时推荐开启centeredSlides: true让激活slide居中,提升视觉效果:
const swiper = new Swiper('.swiper', {
  slidesPerView: 'auto',
  centeredSlides: true,
  watchSlidesProgress: true, // 监听slide的进度与尺寸变化
  on: {
    slideChange: function() {
      // 延迟调用update,确保CSS样式切换完成后再更新布局
      setTimeout(() => {
        this.update();
      }, 100);
    }
  }
});
  1. HTML结构示例
<div class="swiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    <div class="swiper-slide">Slide 3</div>
  </div>
</div>

关键注意事项

  • 不要用内联样式设置slide宽度,会被Swiper的动态生成样式覆盖,通过CSS类控制更稳定。
  • 确保Swiper容器宽度足够,能容纳激活状态的700px slide和两侧的300px slide,避免出现布局溢出问题。
  • 延迟调用update()是因为CSS类切换后浏览器需要时间渲染新样式,直接调用会导致Swiper读取到旧的尺寸值。

内容的提问来源于stack exchange,提问作者tsvetko.krastev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:50:26