Swiper 예제 - 새로고침할 때마다 순서가 바뀌는 슬라이드

Lpla

·

2021. 2. 22. 21:26

반응형

Swiper를 예시 라이브러리로 사용했지만 자바스크립트를 사용하는 기술이므로 다른 어떤 슬라이드도 가능하다.

사전 지식

지난 시간에 여러 가지 방법으로 랜덤 이미지를 구현하는 방법을 알아봤다.

 

[JavaScript] 랜덤 이미지 보여주기

자바스크립트로 랜덤 이미지를 보여주는 방법에 대해 알아보겠다. 0. 기본값 세팅 HTML CSS html, body { width: 100%; height: 100%; margin: 0; } .container { position: relative; width: 100%; height: 100..

lpla.tistory.com

랜덤 슬라이드도 비슷한 맥락이기 때문에 배운 걸 바탕으로 어렵지 않게 구현할 수 있다.

다만 앞선 랜덤 이미지와 랜덤 슬라이드는 결정적인 차이가 존재한다.

랜덤 이미지는 새로고침 후 단 하나의 이미지만 보여주면 되고 그 이후의 상황은 고려하지 않는다.

하지만 랜덤 슬라이드는 처음 보여지는 이미지와 다음에 보여질 이미지들까지 고려해야 한다.

즉 같은 이미지를 두 번 사용해서는 안 되는, 중복을 없애야 한다.

 

참고로 중복을 없애는 방법도 이전에 공부했다.

 

[JavaScript] 무작위 숫자 5개를 뽑아 오름차순으로 정렬 2

지난 포스트 : [JavaScript] 무작위 숫자 5개를 뽑아 오름차순으로 정렬 1 지난 번에 무작위 숫자 5개를 뽑아 오름차순으로 정렬하는 방법에 대해 알아보았다. var 추출 = []; for (i = 1; i <= 5; i+=1) { var..

lpla.tistory.com

이 두 지식을 알고 있다면 어렵지 않다.

먼저 기본 구조를 만들어보자.

 

기본구조

HTML

<head>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/5.4.5/css/swiper.css">
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <!-- Swiper -->
  <div class="swiper-container">
    <div class="swiper-wrapper">
      <div class="swiper-slide"></div>
      <div class="swiper-slide"></div>
      <div class="swiper-slide"></div>
      <div class="swiper-slide"></div>
      <div class="swiper-slide"></div>
      <div class="swiper-slide"></div>
      <div class="swiper-slide"></div>
      <div class="swiper-slide"></div>
      <div class="swiper-slide"></div>
    </div>
  </div>
  
  <!-- jQuery cdn -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/5.4.5/js/swiper.js"></script>
  <script src="script.js"></script>
</body>

 

CSS

.swiper-container { width: 500px; height: 700px; position: relative; }
.swiper-slide { width: 100%; height: 100%; background-size: cover; }
.swiper-slide:nth-child(1) {
  background-image: url(/images/movie01.jpg);
}
.swiper-slide:nth-child(2) {
  background-image: url(/images/movie02.jpg);
}
.swiper-slide:nth-child(3) {
  background-image: url(/images/movie03.jpg);
}
.swiper-slide:nth-child(4) {
  background-image: url(/images/movie04.jpg);
}
.swiper-slide:nth-child(5) {
  background-image: url(/images/movie05.jpg);
}
.swiper-slide:nth-child(6) {
  background-image: url(/images/movie06.jpg);
}
.swiper-slide:nth-child(7) {
  background-image: url(/images/movie07.jpg);
}
.swiper-slide:nth-child(8) {
  background-image: url(/images/movie08.jpg);
}
.swiper-slide:nth-child(9) {
  background-image: url(/images/movie09.jpg);
}

 

JavaScript

var swiper = new Swiper('.swiper-container');

 

결과

 

swiper의 기본 형태로 총 9개의 이미지가 순차적으로 슬라이드된다.

중복을 제외한 랜덤 슬라이드를 구현하기 위해 nth-child() 대신 고유한 클래스명으로 바꾼다.

 

랜덤 슬라이드 (백그라운드)

CSS

.swiper-slide.bg01 {
  background-image: url(/images/movie01.jpg);
}
.swiper-slide.bg02 {
  background-image: url(/images/movie02.jpg);
}
.swiper-slide.bg03 {
  background-image: url(/images/movie03.jpg);
}
.swiper-slide.bg04 {
  background-image: url(/images/movie04.jpg);
}
.swiper-slide.bg05 {
  background-image: url(/images/movie05.jpg);
}
.swiper-slide.bg06 {
  background-image: url(/images/movie06.jpg);
}
.swiper-slide.bg07 {
  background-image: url(/images/movie07.jpg);
}
.swiper-slide.bg08 {
  background-image: url(/images/movie08.jpg);
}
.swiper-slide.bg09 {
  background-image: url(/images/movie09.jpg);
}

bg01부터 bg09까지 클래스명을 정하고 각각 배경 이미지를 추가했다.

이제 bg01부터 bg09가 랜덤한 swiper-slide에 추가된다면 랜덤 슬라이드가 된다.

편의상 제이쿼리와 자바스크립트를 섞어 사용하겠다.

 

JavaScript

$(function () {
  var swiper = new Swiper('.swiper-container');
  var SlideNum = $('.swiper-slide').length;
  var Array = [];
});

먼저 SlideNum 변수에 swiper-slide의 개수를 담는다.

나중에 개수가 변경되더라도 일일이 수정하지 않아도 되니 유용하다.

그리고 빈 Array 변수를 생성한다.

 

$(function () {

  for (i = 1; i <= SlideNum; i += 1) {
    var RandomNum = Math.floor(Math.random() * 9);
    if (Array.indexOf(RandomNum) === -1) {
      Array.push(RandomNum);
      $('.swiper-slide').eq(RandomNum).addClass('bg0' + i + '');

    } else {
      i -= 1;
    }
  }
});

i가 1부터 9까지 되는 동안 반복문을 돌린다.

i는 빈 Array에 0부터 8까지 값을 채워 넣지만 그 값이 중복된다면 i는 증가하지 않는다.

즉 Array는 수십번을 반복하더라도 결국 0부터 8까지 총 9개의 값이 쌓인다.

그리고 빈 Array에 담길 때 그 값은 swiper-slide의 RandomNum번째에 bg0i 클래스를 추가한다.

 

랜덤 슬라이드 (img 태그)

원리는 같다.

 

CSS

.swiper-container { width: 500px; height: 700px; position: relative; }
.swiper-slide { width: 100%; height: 100%; background-size: cover; }
.swiper-slide img { width: 100%; }

클래스명으로 이미지를 추가하는 형태가 아니므로 다른 css를 지우고 img만 width: 100%; 를 맞춘다.

 

JavaScript

$(function () {
  var swiper = new Swiper('.swiper-container');
  var SlideNum = $('.swiper-slide').length;
  var Array = ['/images/movie01.jpg','/images/movie02.jpg','/images/movie03.jpg','/images/movie04.jpg','/images/movie05.jpg','/images/movie06.jpg','/images/movie07.jpg','/images/movie08.jpg','/images/movie09.jpg'];
  for (i = 0; i < SlideNum; i += 1) {
    var RandomNum = Math.floor(Math.random() * 9);
    if (Array.indexOf(RandomNum) === -1) {
      Array.push(RandomNum);
      $('.swiper-slide').eq(i).append(
        '<img src="'+Array[RandomNum]+'">'
      );

    } else {
      i -= 1;
    }
  }
});

이번엔 Array에 이미지경로를 담는다.

백그라운드는 bg01 로 시작했기 때문에 i를 1로 주었지만 지금은 첫번째 배열이 Array[0] 이다.

따라서 반복문도 0부터 8까지 돌리도록 한다.

 

최종 결과

 

 

마무리

이것으로 새로고침할 때마다 순서가 바뀌는 랜덤 슬라이드는 끝이다.

이 글을 적으면서 몇 가지 테스트해보고 싶은 환경이 떠올랐는데 (이 기능이 제대로 작동하지 않을 것 같은 상황) 다음에 가져와보겠다.

 

반응형