🧑‍💻개발/라이브러리

[라이브러리]Swiper의 dot을 커스텀할 수 있는 방법

무택 2023. 7. 19.

 

 

안녕하세요 무택입니다 :)

오늘은 저번 Slick-slider의 dot을 커스텀한 글에 이어서 이번에는 Swiper의 dot을 커스텀하는 방법에 대해서 써보려고 합니다. 아래에서 바로 확인하시죠.

 


Slick-slider의 Dot을 커스텀하는 방법은 아래 글을 참고해 주세요.

https://mu08.tistory.com/107

 


 

Swiper 라이브러리의 Dot을 커스텀하는 방법

HTML/CSS

<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.7/js/swiper.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.7/css/swiper.min.css"/>

<style>
body {
  background: #eee;
  margin: 0;
  padding: 0;
}

.swiper01 {
  width: 100%;
  background-color: #ccc;
}

.swiper-container {
  width: 100%;
  height: 100%;
}

.swiper-slide {
  height: 300px;
  text-align: center;
  line-height: 300px;
  background-color: #ccddff;
}

.swiper-pagination {
  width: 100%;
  background-color: rgba(0, 0, 0, .5);
}

.swiper-pagination-bullet {
  width: calc(100% / 3);
  margin: 0;
  line-height: 40px;
  height: 40px;
  border-radius: 0;
  background-color: none;
}

.swiper-pagination-bullet span{
  color: #fff;
}
</style>

<div class="swiper01">
  <div class="swiper-container">
    <div class="swiper-wrapper">
      <div class="swiper-slide">Swiper 1</div>
      <div class="swiper-slide">Swiper 2</div>
      <div class="swiper-slide">Swiper 3</div>
    </div>
  </div>
</div>
<div class="swiper-pagination"></div>

꼭 swiper의 js파일과 css파일을 불러와야 적용이 됩니다.

 

 

JS

var bullet = ['슬라이드1', '슬라이드2', '슬라이드3'];
var swiper = new Swiper('.swiper-container', {
  pagination: {
    el: '.swiper-pagination',
    clickable: true,
    renderBullet: function (index, className) {
      return '<div class="' + className + '"><span>' + (bullet[index]) + '</span></div>';
    }
  },
});

 

 

Codepen

See the Pen [라이브러리]Swiper 닷 커스텀하기 by TytanLee (@TytanLee) on CodePen.

 

 

 

 

swiper-pagination-bullet클래스에 !important를 넣은 건 codepen상에서 스크립트 적용 문제 때문에 넣게 되었습니다. 실제 적용할 때는 빼도 적용이 될 것 같아요.

 

 

코드설명

1. swiper-pagination클래스를 선언해 줘야 Dot을 사용할 수 있습니다. HTML에 꼭 앞의 클래스를 만들어주세요.

2. JS에서 만들어준 swiper-pagination-bullet클래스를 CSS에서 수정할 수 있습니다.

3. var bullet = ['슬라이드1', '슬라이드2', '슬라이드3'];슬라이드에 들어갈 텍스트를 넣어줄 수 있습니다.

4. 아래 옵션을 이용하면 HTML에 넣고 싶은 divspan 등 코드를 넣을 수 있습니다.

renderBullet: function (index, className) {
  return '<div class="' + className + '"><span>' + (bullet[index]) + '</span></div>';
}