반응형

 

 

Swiper

The Most Modern Mobile Touch Slider

 

웹퍼블리싱 프로젝트를 하다보면 슬라이더는 자주 사용하는 기능 중 하나입니다.

자바스크립트로 직접 코딩해서 만들수도 있겠지만, 고객사의 잦은 기능 변경 및 반응형에 대한 대응들을 생각한다면,

제한된 시간에 웹퍼블리싱 해야하기에 라이브러리(플러그인)를 사용하는 것이 작업에 효율적입니다.

많은 라이브러리들이 있지만 제가 사용하는 Swiper Slider 기능에 대해서 포스팅 하겠습니다.

 

Swiper는 다양한 사용자 옵션을 제공하고 있기에 사용하기 편리한 무료 라이브러리(플러그인) 입니다.

웹사이트, 모바일 네이티브, 하이브리드 앱 모두 호환하여 사용 가능합니다. 

Swiper의 기본설치 방법과 옵션에 대해서는 '반응형 슬라이더 Swiper (사용 방법/예제) 웹퍼블리싱' 참조 부탁드립니다.

 

프로젝트를 하다보면 2개의 슬라이더를 연동해서 제어해야 할 때가 있습니다.

이번에는 이를 해결하기 위한 Swiper API 에 대하여 알아 보겠습니다.

그 외에 이번 포스팅은 Swiper 라이브러리(플러그인)에서 많이 사용하는 기능에 대해서 종합적으로 정리하였습니다.

 

 

 

 

 

Swiper API - Controller

 

웹퍼블리싱 프로젝트를 하다보면 슬라이더 2개를 서로 연동하여 동작될수 있도록 구현해야 할 경우가 발생합니다.

여기서 말하는 연동이란?

A라는 Main 슬라이더가 있고 B라는 Thumbnail 슬라이더가 있다고 가정할 때, 

A라는 슬라이더를  동작할 경우 B라는 슬라이더도 동일하게 슬라이딩되고,

B라는 슬라이더를 동작하더라도 A라는 슬라이더가 동일하게 슬라이딩 되는, A와 B가 서로 연동되어 제어 가능한 상태를 말합니다.

이럴경우 Swiper API 중에서 Controller 모듈을 사용하면 문제를 해결할 수 있습니다.

지금부터 사용방법에 대해 쉽게 설명 드리겠습니다.

 

 

 

 

 

Use Swiper from CDN

 

Swiper 라이브러리(플러그인)를 사용하기 위한 설치방법은 여러가지가 있습니다.

이전에 포스팅한 Swiper Installation 중에서 CDN을 이용한 방법을 설명하지 않아서 CDN으로 Swiper Library를 사용하여 설명하겠습니다.

 

<link rel="stylesheet" href="https://unpkg.com/swiper@7/swiper-bundle.min.css" />
<script src="https://unpkg.com/swiper@7/swiper-bundle.min.js"></script>

 

 

 

 

 

Swiper API 사용 방법

 

Swiper 슬라이더를 2개로 연동 및 제어하기 위한 HTML 구조, JavaScript, Swiper 메서드 옵션에 대해 종합적으로 상세하게 설명하여 진행하겠습니다.

그리고 이 글의 작성 이유인 Swiper API 중 controller 파라미터 사용법에 대해서 다루어 보겠습니다.

 

 

HTML 

서로 연동되어 슬라이드 되어야 할 Main Swiper 와 Thumbnail Swiper를 마크업하여 만들고,

Swiper JS와 Swiper CSS 라이브러리를 CDN으로 연결합니다.

<!DOCTYPE html>
<html lang="ko">
<head>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta http-equiv="X-UA-Compatible" content="IE=Edge">
	<meta charset="utf-8">
	<title>Swiper - Swiper 2개 연동과 제어(Controller)</title>
	<link rel="stylesheet" href="css/reset.css">
	<link rel="stylesheet" href="https://unpkg.com/swiper@7/swiper-bundle.min.css">
</head>
<body>
<div class="swiper-container gallery-top">
	<div class="swiper-wrapper">
		<div class="swiper-slide"><div class="swiper-slide-container">Slide 1</div></div>
		<div class="swiper-slide"><div class="swiper-slide-container">Slide 2</div></div>
		<div class="swiper-slide"><div class="swiper-slide-container">Slide 3</div></div>
		<div class="swiper-slide"><div class="swiper-slide-container">Slide 4</div></div>
		<div class="swiper-slide"><div class="swiper-slide-container">Slide 5</div></div>
	</div>
	<div class="swiper-pagination"></div>
</div>
<div class="wrap_thumb_layout">
	<div class="swiper-container gallery-thumbs">
		<div class="swiper-wrapper">
			<div class="swiper-slide"><div class="swiper-slide-container">Slide 1</div></div>
			<div class="swiper-slide"><div class="swiper-slide-container">Slide 2</div></div>
			<div class="swiper-slide"><div class="swiper-slide-container">Slide 3</div></div>
			<div class="swiper-slide"><div class="swiper-slide-container">Slide 4</div></div>
			<div class="swiper-slide"><div class="swiper-slide-container">Slide 5</div></div>
		</div>
	</div>
	<!-- Add Arrows -->
	<div class="swiper-button-next"></div>
	<div class="swiper-button-prev"></div>
</div>
</body>
</html>

 

 

JavaScript

Swiper 슬라이더를 동작시키기 위해서는 JavaScript에서 Swiper를 초기화하고 필요한 기능에 대해서는 Swiper 메서드 옵션을 사용해야 합니다.

여기까지 작업을 완료하면  Main Swiper 와 Thumbnail Swiper 연동되지 않고 각각 동작하는 것을 확인할 수 있습니다.

사용해야 할 Swiper  옵션설명 및 사용방법은 아래와 같습니다.

  • spaceBetween : 슬라이드 간격 설정 
  • pagination : 페이징 사용자 설정(type : bullets, fraction, progressbar)
  • loop : 슬라이드 반복 여부 설정
  •  loopedSlides : loop 값이 true 일 경우 파라미터 duplicate 개수 설정
  • navigation : 네비게이션 사용자 설정(이전, 다음 버튼 설정)
  • slidesPerView : 한번에 보여지는 슬라이드 개수 설정
  • centeredSlides : 슬라이드 중앙 배치 여부 설정 
  • touchRatio : 드래그 비율 설정(기본값: 1, 값을 0으로 변경할 경우 드래그 불가능)
  • slideToClickedSlide : 슬라이드가 여러개 나열되어 있을 경우, 클릭시 해당 슬라이드 위치로 이동 여부 설정 

 

<script>
	var swiperTopNum = $('.gallery-top').find('.swiper-slide');
	var swiperSubNum = $('.gallery-thumbs').find('.gallery-thumbs');

	var galleryTop = new Swiper('.gallery-top', {
    	spaceBetween: 10,	//슬라이드 간격
        pagination: {	//페이징 사용자 설정
        	el: ".swiper-pagination",	//페이징 태그 클래스 설정 
			clickable: true,	//버튼 클릭 여부
			type : 'bullets',	//페이징 타입 설정(종류: bullets, fraction, progressbar)
			// Bullet Numbering 설정
        	renderBullet: function (index, className) {
        		return '<span class="' + className + '">' + (index + 1) + "</span>";
        	},
		},
		loop: true,	//슬라이드 반복
		loopedSlides: swiperTopNum.length	//loop 시 파라미터 duplicate 개수 - 정적으로 숫자 4 표현 가능
    });

    var galleryThumbs = new Swiper('.gallery-thumbs', {
    	spaceBetween: 0,	//슬라이드 간격
    	navigation: {	//네비게이션 사용자 설정
    		nextEl: '.swiper-button-next',	//다음 버튼 클래스 설정
        	prevEl: '.swiper-button-prev',	//이전 버튼 클래스 설정
    	},
    	centeredSlides: true,	//슬라이드 중앙 배치
    	slidesPerView: 'auto',	//한번에 보여지는 슬라이드 개수(auto 가능)
    	touchRatio: 0.2,	//드래그 비율 설정(기본값: 1, 기본값을 0으로 설정할 경우 드래그 불가능)
    	slideToClickedSlide: true,	//슬라이드가 여러개 나열되어 있을 경우, 클릭 시 해당 슬라이드 위치로 이동
		loop: true,	//슬라이드 반복
		loopedSlides: swiperSubNum.length //loop 시 파라미터 duplicate 개수 - 정적으로 숫자 4 표현 가능
    });
</script>

 

 

Swiper API - controller

각각 동작하는 Main Swiper 와 Thumbnail Swiper를 서로 연동하여 제어하려면, 어떻게 해야 할까요?

Main Swiper는 Thumbnail Swiper에 연결하고, Thumbnail Swiper는 Main Swiper에 연결하고 제어해야 합니다.

이를 위해서 Swiper의 controller 모듈의 control의 파라미터 옵션을 사용한다면 Main Swiper 와 Thumbnail Swiper를 연결하여 제어할 수 있습니다.

사용방법은 및 Swiper API controller 명세서는 아래와 같습니다.

 

galleryTop.controller.control = galleryThumbs;
galleryThumbs.controller.control = galleryTop;

 

 

JavaScript  + Swiper API

JavaScript와 Swiper API의 controller를 결합한 스크립트 전체 코드는 아래와 같습니다.

	var swiperTopNum = $('.gallery-top').find('.swiper-slide');
	var swiperSubNum = $('.gallery-thumbs').find('.gallery-thumbs');

	var galleryTop = new Swiper('.gallery-top', {
    	spaceBetween: 10,	//슬라이드 간격
        pagination: {	//페이징 사용자 설정
        	el: ".swiper-pagination",	//페이징 태그 클래스 설정 
			clickable: true,	//버튼 클릭 여부
			type : 'bullets',	//페이징 타입 설정(종류: bullets, fraction, progressbar)
			// Bullet Numbering 설정
        	renderBullet: function (index, className) {
        		return '<span class="' + className + '">' + (index + 1) + "</span>";
        	},
		},
		loop: true,	//슬라이드 반복
		loopedSlides: swiperTopNum.length	//loop 시 파라미터 duplicate 개수 - 정적으로 숫자 4 표현 가능
    });

    var galleryThumbs = new Swiper('.gallery-thumbs', {
    	spaceBetween: 0,	//슬라이드 간격
    	navigation: {	//네비게이션 사용자 설정
    		nextEl: '.swiper-button-next',	//다음 버튼 클래스 설정
        	prevEl: '.swiper-button-prev',	//이전 버튼 클래스 설정
    	},
    	centeredSlides: true,	//슬라이드 중앙 배치
    	slidesPerView: 'auto',	//한번에 보여지는 슬라이드 개수(auto 가능)
    	touchRatio: 0.2,	//드래그 비율 설정(기본값: 1, 기본값을 0으로 설정할 경우 드래그 불가능)
    	slideToClickedSlide: true,	//슬라이드가 여러개 나열되어 있을 경우, 클릭 시 해당 슬라이드 위치로 이동
		loop: true,	//슬라이드 반복
		loopedSlides: swiperSubNum.length //loop 시 파라미터 duplicate 개수 - 정적으로 숫자 4 표현 가능
    });

	//Main Swiper와 Thumbnail Swiper가 연동제어 서로를 제어
    galleryTop.controller.control = galleryThumbs;
    galleryThumbs.controller.control = galleryTop;

 

 

 

 

 

Swiper 구현 화면 및 예제 다운로드

 

위에 'Swiper 슬라이더를 2개로 연동 및 제어하기' 설명에 대한 실제 구현한 화면과 포스팅한 예제를 만들어 다운로드 받아서 공부하실 수 있도록 하였습니다.

다운로드 예제는 구현된 화면은 같으나 Swiper 옵션인 loopedslides 적용한 방법과 적용하지 않은 방법 2개로 만들었습니다.

swiper.css 에서 .gallery-thumbs 클래스 내용중 overflow: hidden; 속성을 주석처리 하고 보시면,

Swiper 옵션인 loopedslide  에 대해서 위에서 설명드렸지만 적용된 여부의 차이점을 확인하실 수 있으리라 생각됩니다.  

 

  Swiper - '슬라이더 2개 연동 제어' 예제 실습 파일  

swiper.zip
0.03MB

 

 

 

 

 

마치며..

 

웹퍼블리싱 프로젝트를 하다보면 꼭 빠지지 않는 요소가 슬라이더라고 생각 됩니다.

때문에 경력이 있는 웹퍼블리셔들은 주로 사용하는 슬라이더 라이브러리가 1~2개 쯤은 있다고 생각됩니다.

슬라이더 라이브러리는 아주 많이 존재합니다.

저도 몇 년 동안 프로젝트를 하면서 항상 슬라이드 구현은 빠지지 않았기에 여러가지 라이브러리를 사용하면서 저에게 맞는 라이브러리를 찾게 되었고,

Swiper Slider 를 현재는 주로 사용하고 있습니다.

매번 프로젝트 마다 사용하는 슬라이더이기에 쉽게 구현할수 있다고 생각하면 쉽지만, 상황에 따라 고객사의 요구사항이 복잡한 경우도 종종 발생합니다.

이럴경우 기본 라이브러 옵션만 가지고는 구현이 불가능하기 때문에 슬라이더 라이브러리에서 제공하는 API와 파라미터가 중요합니다.

Swiper 라이브러리(플러그인)는 이런부분 또한 디테일하게 제공하고 있기에 완성도가 높은 라이브러리라고 생각이 됩니다.

이번에 포스팅한 내용은 프로젝트에서 종종 발생하는 라이브러리의 기본옵션만 가지고 구현할 수 없는 내용에 대하여 다루었습니다.

이 글을 통해서 후배 웹퍼블리셔 분들께서 프로젝트에 투입되어 당황하지 않고, 문제를 조금더 쉽게 해결할 수 있도록 도움이 되었으면 합니다.

 

 

반응형
반응형

안녕하세요, 맑은커뮤니케이션의 퍼블리셔 윤상원입니다.

오늘은 IE10 이상을 지원하는 페이지 작업을 할 때 유용하게 쓰이는 Swiper에 대해 정리해보았습니다.

 

 

 

사용 방법

 

1단계: 연결(두 가지 방법)

 

 

1. 파일을 다운로드하지 않고 html에서 CDN 연결

<link rel="stylesheet" href="https://unpkg.com/swiper/css/swiper.min.css">

 

 

2. 파일을 다운로드해서 html 연결

https://github.com/nolimits4web/swiper/archive/v5.3.0.zip

 

 

예시)

<!DOCTYPE html>
<html lang="ko">
<head>
    ...
    <link rel="stylesheet" href="path/to/swiper.min.css">
</head>
<body>
    ...
    <script src="path/to/swiper.min.js"></script>
</body>
</html>

CSS, JS 파일은 package 폴더 안에서 찾아볼 수 있습니다.

 

 

2단계: 기본 레이아웃 추가

<div class="swiper-container">
    <div class="swiper-wrapper">
        <div class="swiper-slide">Slide 1</div>
        <div class="swiper-slide">Slide 2</div>
        <div class="swiper-slide">Slide 3</div>
        ...
    </div>
</div>

swiper-container > swiper-wrapper > swiper-slide 순으로 감싸져있어야 하고,

swiper-slide가 슬라이드의 내용이 됩니다.

 

 

 

3단계: 자바스크립트에서 Swiper 초기화

new Swiper('.swiper-container');

swiper-container라는 클래스 이름은 변경하지 않아야 합니다.

 

 

예제

See the Pen 간단한 스와이퍼 예제 by 윤 시대 (@yoonsangwon) on CodePen.

 

 

다른 옵션을 넣지 않고 1번부터 3번까지의 내용을 적용한 예제입니다.

 

 

 

 

슬라이드 옵션

 

Swiper에는 다양한 옵션들이 있습니다.

옵션을 사용하면 마우스로만 움직이는 슬라이드를 버튼 클릭으로 움직이게 하거나,

아무런 동작을 하지 않아도 자동으로 슬라이드가 넘어가게 하는 등 사용자가 더 편리하게 이용할 수 있습니다.

 

 

슬라이드 옵션 예제

See the Pen 슬라이드 옵션 by 윤 시대 (@yoonsangwon) on CodePen.

 

 

예제처럼 필요한 옵션과 값을 적어주면 적용할 수 있습니다.

동작이 아닌 버튼이나 스크롤 바가 생기는 등의 옵션은 해당 html 코드도 같이 넣어주어야 합니다.

 

 

옵션 적용하는 방법

사용방법 3번이 Swiper를 초기화하는 방법(한 줄)이었다면 옵션을 추가할 때는 코드의 모양이 바뀌어야 합니다.(여러 줄)

 

옵션이 필요없을 때

new Swiper('.swiper-container');

 

옵션을 적용해야 할 때

var mySwiper = new Swiper('.swiper-container', {

   // 여기에 옵션을 넣어야 합니다.

});

 

 

자주 사용하는 옵션 목록 ('더보기'를 클릭하면 옵션을 볼 수 있습니다)

 

Navigation(페이지를 넘기는 버튼)

더보기

[HTML]

<div class="swiper-button-prev"></div> // 이전 페이지
<div class="swiper-button-next"></div> // 다음 페이지

[Javascript]

var mySwiper = new Swiper('.swiper-container', {
  navigation: {
    prevEl: '.swiper-button-prev',
    nextEl: '.swiper-button-next',
  },
});

See the Pen rNVevqd by 윤 시대 (@yoonsangwon) on CodePen.

 

 

Pagination(페이지의 순서를 나타내는 불릿)

더보기

[HTML]

<div class="swiper-pagination"></div>

[Javascript]

var mySwiper = new Swiper('.swiper-container', {
  pagination: {
    el: '.swiper-pagination',
    type: 'bullets',
  },
});

See the Pen WNvwJLp by 윤 시대 (@yoonsangwon) on CodePen.

 

 

자동 재생(1000 = 1초)

더보기

[Javascript]

var mySwiper = new Swiper('.swiper-container', {
  autoplay: {
    delay: 2000,
  },
});

See the Pen ExjKLGe by 윤 시대 (@yoonsangwon) on CodePen.

 

 

한 번에 여러 장의 슬라이드를 표현하는 방법 + 슬라이드 무한 반복

더보기

[Javascript]

var swiper = new Swiper('.swiper-container', {
    slidesPerView: 3, // 보여지는 슬라이드 수
    spaceBetween: 30, // 슬라이드 간의 거리(px 단위)
    loop: true, // 슬라이드 무한 반복
    centeredSlides: true, // 다음 슬라이드의 모습이 50%만 보입니다.(중앙)
});

See the Pen xxGVJZO by 윤 시대 (@yoonsangwon) on CodePen.

 

 

스와이퍼 홈페이지에서 더 많은 옵션과 예제를 확인할 수 있습니다.

옵션:  https://swiperjs.com/api/

예제:  https://swiperjs.com/demos/

 

 

 

홈페이지에는 나오지 않는 방법들

한 페이지에서 스와이퍼를 여러 번 사용해야 할 때 선언하는 방법

더보기

스와이퍼를 한 페이지에서 여러 번 사용할 때가 있습니다.

그럴 때는 swiper-container 클래스마다 추가로 클래스를 넣고, 각자의 클래스를 스크립트에 선언해주면 됩니다.

 

[HTML]

// 첫번째 슬라이드입니다.
<div class="swiper-container swiper1">
    <div class="swiper-wrapper">
        <div class="swiper-slide">Slide 1</div>
        <div class="swiper-slide">Slide 2</div>
        <div class="swiper-slide">Slide 3</div>
    </div>
</div>

// 두번째 슬라이드입니다.
<div class="swiper-container swiper2">
    <div class="swiper-wrapper">
        <div class="swiper-slide">Slide 1</div>
        <div class="swiper-slide">Slide 2</div>
        <div class="swiper-slide">Slide 3</div>
    </div>
</div>

 

[Javascript]

// 첫번째 슬라이드에 추가한 클래스를 선언해주세요.
var swiper1 = new Swiper('.swiper1', {

	// 옵션을 넣어주세요.
});

// 두번째 슬라이드에 추가한 클래스를 선언해주세요.
var swiper2 = new Swiper('.swiper2', {

	// 옵션을 넣어주세요.
});

 

 

 

슬라이드 버튼을 swiper-container 밖으로 이동시키는 방법

더보기

작업을 하다보면 슬라이드의 버튼을 컨테이너 밖으로 이동시키고 싶은데 화면에서 사라질 때가 있습니다.

그 이유는 .swiper-container 안에 들어간 overflow:hidden 속성 때문인데요,

슬라이드를 사용하기 위해선 overflow 속성을 끌 수 없으니 이 방법을 사용하면 해결할 수 있습니다.

 

[HTML] - 기존

<div class="swiper-container">
    <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-button-prev"></div> <!-- 이전 페이지 -->
    <div class="swiper-button-next"></div> <!-- 다음 페이지 -->
</div>

 [HTML] - 수정 후

<div> // 임의의 DIV
    <div class="swiper-container">
        <div class="swiper-wrapper">
            <div class="swiper-slide">슬라이드 1</div>
            <div class="swiper-slide">슬라이드 2</div>
            <div class="swiper-slide">슬라이드 3</div>
        </div>
    </div>
    
    <div class="swiper-button-prev"></div> <!-- 이전 페이지 -->
    <div class="swiper-button-next"></div> <!-- 다음 페이지 -->
</div>

기존에 .swiper-container 안에 있던 버튼 두 가지를 밖으로 빼내고 전체를 임의의 div를 새로 감싼 모습입니다.

그리고 이제 새로 감싼 div에 position:relative를 추가하고,

.swiper-container에 있던 position:relative를 position:static 으로 변경해주시면 됩니다.

 

[결과 화면]

 

 

감사합니다.

반응형

+ Recent posts