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

Splidejs+Bootstrap响应式标签转折叠面板:移动端切桌面端内容不显示

问题解决:Bootstrap标签与Splidejs断点切换后内容不显示

问题分析

窗口从移动端分辨率切换回991px以上时,Splide在移动端被销毁后未重新初始化,同时Bootstrap标签的激活状态与Splide滑块状态脱节,导致标签内容无法正常显示。

修复方案

1. 调整Splide生命周期与状态同步逻辑

移除原配置中的destroy: true,改为通过窗口resize事件手动管理Splide的初始化/销毁,同时确保Bootstrap标签与滑块状态始终同步。

2. 修正后的JavaScript代码

let splide = null;
const breakpoint = 991;

// 初始化Splide及事件绑定
function initSplide() {
  if (splide) return;
  splide = new Splide('.splide', {
    type: 'fade',
    rewind: true,
    speed: 700,
    arrows: false,
    autoplay: true,
    pagination: false,
    pauseOnFocus: true,
  });

  splide.mount();
  const { Drag } = splide.Components;
  Drag.disable(true);

  // 滑块切换时同步Bootstrap标签
  splide.on('moved', (newIndex) => {
    const tabElement = document.getElementById(`tab${newIndex + 1}-tab`);
    if (tabElement) new bootstrap.Tab(tabElement).show();
  });

  // 点击标签时同步滑块位置
  document.querySelectorAll('[data-bs-toggle="pill"]').forEach((tab, index) => {
    tab.addEventListener('click', () => {
      if (splide && index >= 0 && index < splide.length) splide.go(index);
    });
  });
}

// 销毁Splide实例
function destroySplide() {
  if (splide) {
    splide.destroy();
    splide = null;
  }
}

// 处理窗口尺寸变化
function handleResize() {
  const windowWidth = window.innerWidth;
  if (windowWidth > breakpoint) {
    initSplide();
    // 同步当前激活的标签到滑块
    const activeTab = document.querySelector('[data-bs-toggle="pill"].active');
    if (activeTab) {
      const tabIndex = Array.from(document.querySelectorAll('[data-bs-toggle="pill"]')).indexOf(activeTab);
      splide?.go(tabIndex);
    }
  } else {
    destroySplide();
  }
}

// 初始加载执行一次
handleResize();
// 监听窗口resize事件
window.addEventListener('resize', handleResize);

3. HTML结构优化(可选)

确保桌面端折叠面板始终显示,避免状态残留:

<div id="collapseOne" class="accordion-collapse collapse d-lg-block my-1 my-lg-0" aria-labelledby="headingOne" data-bs-parent="#tabData">

关键修复点

  • 取消Splide断点配置中的destroy: true,改用手动管理生命周期,保证桌面端能重新初始化实例
  • 添加窗口resize监听,切换断点时同步Bootstrap标签与Splide滑块的激活状态
  • 修正原代码中的变量错误(splideDatiRGS应为splide)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 10:10:55