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

Swiper JS中swiper.destroy()失效,窗口resize时无法销毁轮播实例求助

Swiper JS窗口resize时销毁实例无效的解决方案

问题根源

你代码的核心问题是每次调用initTopInfoContainerSwiper函数时,都会在函数内部新建一个Swiper实例,导致你调用swiper.destroy()时,销毁的是刚创建的新实例,而非之前已经初始化并在页面上运行的那个实例。

修正后的代码

$(document).ready(() => {
  initTopInfoContainerSwiper()
})

$(window).resize(() => {
  initTopInfoContainerSwiper()
})

let swiperInitParam = true;
let swiperDestroyParam = false;
let swiper = null; // 将swiper变量提升到外部,作为共享实例

const initTopInfoContainerSwiper = () => {
  // 只有当实例不存在时,才创建新的Swiper实例
  if (!swiper) {
    swiper = new Swiper('#js__swipper-top-wrapper-index', {
      init: false,
      speed: 400,
      slidesPerView: 1,
      centerInsufficientSlides: true,
      spaceBetween: 15,
      loop: true,
    });
  }

  if (window.innerWidth <= 1000) {
    if (swiperInitParam) {
      swiper.init();
      swiperInitParam = false;
      swiperDestroyParam = true;
    }
  } 
  else {
    if (swiperDestroyParam && swiper) {
      swiper.destroy(true); // 传入true彻底移除Swiper添加的元素和事件
      swiper = null; // 销毁后重置实例,下次可重新创建
      swiperDestroyParam = false;
      swiperInitParam = true;
    }
  }
}

关键改动说明

  • 将swiper变量从函数内部移到外部,确保整个作用域内操作的是同一个实例
  • 创建实例前先判断swiper是否为null,避免重复创建无效实例
  • 销毁时传入true参数,彻底清除Swiper生成的DOM元素和绑定的事件
  • 销毁后将swiper重置为null,保证下次进入小屏时能重新创建有效实例

额外优化提示

窗口resize事件触发频率很高,建议添加防抖处理避免频繁执行逻辑:

let resizeTimeout;
$(window).resize(() => {
  clearTimeout(resizeTimeout);
  resizeTimeout = setTimeout(() => {
    initTopInfoContainerSwiper();
  }, 200); // 200ms防抖延迟,可按需调整
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 06:45:37