본문 바로가기

JavaScript

[#. Swiper] Swiper 슬라이드 작동 안 될 때 해결하기

반응형

 

 

 

 

 

 

https://swiperjs.com/

 

Swiper - The Most Modern Mobile Touch Slider

Swiper is the most modern free mobile touch slider with hardware accelerated transitions and amazing native behavior.

swiperjs.com

 

 

팝업을 띄우고 팝업 안에서 swiper를 사용하려고 한다

 

 

① HTML

 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.css" />
    <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css" />
    <script type="text/javascript" src="https://unpkg.com/swiper/swiper-bundle.js"></script>
    <script type="text/javascript" src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>
  </head>
  
  <body>
    <div class="swiper-popup mySwiper">
      <div class="swiper-wrapper">
        <div class="swiper-slide">
          1
        </div>
        <div class="swiper-slide">
          2
        </div>
        <div class="swiper-slide">
          3
        </div>
      </div>
      <div class="swiper-pagination"></div>
    </div>
  </body>
</html>

 

 

 

 

② JS

 

var swiperPopup = new Swiper('.swiper-popup', {
  // Optional parameters
  direction: 'horizontal',		// 가로 슬라이드
  slidesPerView: 1,			// 한 영역에 보이는 슬라이드 수
  spaceBetween: 16,

  // If we need pagination
  pagination: {
    el: '.swiper-page',
  },
})

 

 

 

 

근데 잘 뜨던 swiper가 작동하지 않고 버벅거리는 문제가 발생했다

 

 

 

 

 

 

 

팝업 형태로 swiper를 사용했을 때, 페이지를 로딩한 직후에는 작동하지 않고 어떤 액션이 있어야 작동하게 된다

근데 팝업은 보통 display:none => display:block의 변화를 통해 노출되는데 이 때 swiper가 css 변화를 액션으로 감지하지 못 하는 것 같다

그렇기 때문에 observer 옵션을 추가해 주면 된다

 

 

 

var swiperPopup = new Swiper('.swiper-popup', {
  // Optional parameters
  direction: 'horizontal',		// 가로 슬라이드
  slidesPerView: 1,			// 한 영역에 보이는 슬라이드 수
  spaceBetween: 16,

  // If we need pagination
  pagination: {
    el: '.swiper-page',
  },
  observer: true,	// 추가
  observeParents: true,	// 추가
})

 

observer 옵션을 true로 설정하게 되면

스타일을 변경하거나(예: 숨기기/표시) 하위 요소를 수정(슬라이드 추가/제거)할 때마다 스위퍼가 업데이트(초기화)된다

 

 

 

 

 

 

반응형