首页 > 解决方案 > Swiper JS destroy()不触发

问题描述

我正在尝试使用该功能在移动设备以外的任何设备上禁用 Swiper JS ( https://github.com/nolimits4web/swiperdestroy() ) ,但出现错误Uncaught TypeError: swiper.destroy is not a function

我尝试了各种不同的东西,但我无法让它工作。

import Swiper from 'swiper';

const ImageCarousel = $el => {
  let swiper = Swiper;
  let init = false;

  function swiperMode() {
    let mobile = window.matchMedia('(min-width: 0px) and (max-width: 768px)');
    let tablet = window.matchMedia('(min-width: 769px) and (max-width: 1024px)');
    let desktop = window.matchMedia('(min-width: 1025px)');

    // Enable (for mobile)
    if (mobile.matches) {
      if (!init) {
        init = true;
        const MySwiper = new Swiper('.swiper-container-cta', {
          direction: 'horizontal',
          loop: false,
          speed: 1000,
          grabCursor: true,
          watchSlidesProgress: false,
          mousewheelControl: true,
          keyboardControl: true,
          width: 280,
          spaceBetween: 16,
        });
      }
    }

    // Disable (for tablet)
    else if (tablet.matches) {
      swiper.destroy();
      init = false;
    }

    // Disable (for desktop)
    else if (desktop.matches) {
      swiper.destroy();
      init = false;
    }
  }

  // console.log(swiper);

  window.addEventListener('load', () => {
    swiperMode();
  });

  window.addEventListener('resize', () => {
    swiperMode();
  });
};

export default ImageCarousel;

标签: javascriptcarouselresponsiveswiperswiperjs

解决方案


推荐阅读