Swiperでスライド要素が1つの時、カスタムナビゲーションを非表示にする

Filed under: JavaScript,swiper — kdcs @ 25年11月6日 木曜日

swiperでページネーションやナビゲーションボタンを.swiperの外側に出して表示位置をカスタマイズしているとき、スライド要素が1つしかない場合はナビゲーションを非表示にしておきたい。

以下のオプション設定で、スライド要素の数を確認し、1つの場合はstyleでdisplay:noe;を付けて非表示にする。
※基本的には、’#eventAd .custom-navigation’これだけをdisplay:noneにすればよい

const swiper2 = new Swiper('.eventAdSlider', {
  loop: true,
  parallax: true, // パララックスさせる
  allowTouchMove: false, // マウスでのスワイプを禁止
  speed: 1500,
  autoplay: {
    delay: 5000, // 5秒ごとに自動再生
    disableOnInteraction: false, // ユーザー操作後も自動再生を継続
  },
  pagination: {
    el: '#eventAd .swiper-pagination',
  },
  navigation: {
    nextEl: '#eventAd .swiper-button-next',
  },
  on: {
    init: function () {
// スライド要素が1つの場合、カスタムナビ非表示(loop:true の場合、クローン要素も含まれるので注意)
      const realSlideCount = this.slides.filter(slide => !slide.classList.contains('swiper-slide-duplicate')).length;
      if (realSlideCount <= 1) {
        document.querySelector('#eventAd .custom-navigation').style.display = 'none';
        document.querySelector('#eventAd .swiper-button-next').style.display = 'none';
        document.querySelector('#eventAd .swiper-button-prev').style.display = 'none';
        document.querySelector('#eventAd .swiper-pagination').style.display = 'none';
      }
    }
  }
});

非表示にする必要が無い場合はこちら

const swiper2 = new Swiper('.eventAdSlider', {
  loop: true,
  parallax: true, // パララックスさせる
  allowTouchMove: false, // マウスでのスワイプを禁止
  speed: 1500,
  autoplay: {
    delay: 5000, // 5秒ごとに自動再生
    disableOnInteraction: false, // ユーザー操作後も自動再生を継続
  },
  pagination: {
    el: '#eventAd .swiper-pagination',
  },
  navigation: {
    nextEl: '#eventAd .swiper-button-next',
  },
});

サイト内検索

カテゴリー

最近の投稿

« |Swiperでスライド要素が1つの時、カスタムナビゲーションを非表示にする| »
↑上に戻る