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

Swiper仅移动端加载 初始宽度>768px时调用destroy方法报错

错误原因
  • 页面初始加载宽度大于768px时,代码从未执行Swiper实例化逻辑,此时swiper变量存储的是全局引入的Swiper构造函数本身,而非实例化后的Swiper对象。destroy是Swiper实例的原型方法,并不存在于构造函数上,直接调用就会抛出类型错误。
  • 原有逻辑缺少实例存在性校验:即使是之前初始化过实例的场景,首次销毁后如果反复触发resize事件进入桌面端分支,会重复调用已销毁实例的destroy方法,同样会触发报错。
修复方法

调整逻辑:仅在确认Swiper实例已经完成初始化、实例对象真实存在时,才执行销毁操作,销毁后重置实例变量避免重复调用。初始状态下将swiper变量赋值为null而非Swiper构造函数,从根源上避免误调用构造函数的方法。

修复后的完整代码如下:

/* Swiper Slider Cards Home - Show only on mobile */
var swiper = null;
var init = false;
function swiperMode() {
  let mobile = window.matchMedia("(min-width: 0px) and (max-width: 768px)");

  if (mobile.matches) {
    if (!init) {
      init = true;
      swiper = new Swiper(".slider-cards-js", {
        direction: "horizontal",
        slidesPerView: "auto",
        centeredSlides: true,
        spaceBetween: 32,
        pagination: {
          el: ".swiper-pagination",
          clickable: true,
        },
      });
    }
  } else {
    if (init && swiper) {
      swiper.destroy();
      swiper = null;
      init = false;
    }
  }
}

window.addEventListener("load", function () {
  swiperMode();
});

window.addEventListener("resize", function () {
  swiperMode();
});

补充优化:如果需要减少resize事件频繁触发的性能消耗,可以给swiperMode方法加防抖处理,避免窗口调整过程中反复执行判断逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 02:57:32