Loading...
모바일에 가장 최적화된 스와이프 라이브러리 Swiper API (1편 - 초급)
REDINFO
몇달 전 2023-07-23 01:39:54

싸이트를 운영하다보면 멋진 슬라이드 기능을 구현하고 싶을때가 있다. 무작정 JAVASCRIPT 를 이용하여 만들기엔 너무 어렵기 때문에 시중에 오픈된 라이브러리를 이용하게 되는데 그중 모바일에 가장 친화적인 Swiper API가 있다. 

 

Swiper API는 업데이트도 꾸준히 되고 있으며 초기에 발생되었던 많은 버그들이 지속적으로 업데이트되어 현재는 거의 완벽한 형태의 스와이프 기능을 구현할 수 있다. 물론 이와 함께 유명한 bxSlider 라이브러리도 있지만  모바일에서는 역시나 Swiper API를 따라올 수 없는것같다. 해당 라이브러리의 공식 사이트는 아래와 같다. 

 

 
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 API를 이용할 수 있도록 라이브러리를 로드하 후 간단한 텍스트형 슬라이드를 구현하는 예제는 아래와 같다. 

 

<!-- Swiper API 로드 -->
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.css"/>
<script src="//cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.js"></script>

<div class="api-swiper">
    <div class="swiper-wrapper">
        <div class="swiper-slide">슬라이드 1</div>
        <div class="swiper-slide">슬라이드 2</div>
        <div class="swiper-slide">슬라이드 3</div>
        <div class="swiper-slide">슬라이드 4</div>
    </div>
</div>

<style>
.api-swiper {width: 600px;height: 300px;margin:0 auto;border:solid 1px #333; overflow: hidden;}  
.api-swiper .swiper-wrapper .swiper-slide{ width:100%; height:100%; position: relative;display: flex;justify-content: center; align-items: center;}
</style>

<script>
const swiper = new Swiper('.api-swiper', {
  direction: 'horizontal',
  loop: true,
});  
</script>

 

| 결과

 

기본적으로 터치가 되기 때문에 마우스로 슬라이드하면 페이지가 전환된다. 위와 같이 간단한 소스만으로도 적용이 가능하다. 그럼 두번째로 페이징 기능을 구현해 보도록 하자. 물론 Swiper API에서 자체 제공되는 API가 있으나 실 서비스에 그대로 사용할 수는 없으니 기본적인 메서드형태로 사용할 수 있도록 처리해야한다.  방법은 아래와 같다. 

 

<!-- Swiper API 로드 -->
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.css"/>
<script src="//cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.js"></script>

<!-- jquery 라이브러리 로드 -->
<script src="//code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>

<div class="container">
    <div class="pn prev"><a href="#none" onclick="return false;" class="btn">〈</a></div>
    <div class="pn next"><a href="#none" onclick="return false;" class="btn">〉</a></div>
    <div class="api-swiper">
        <div class="swiper-wrapper">
            <div class="swiper-slide">슬라이드 1</div>
            <div class="swiper-slide">슬라이드 2</div>
            <div class="swiper-slide">슬라이드 3</div>
            <div class="swiper-slide">슬라이드 4</div>
        </div>
    </div>
</div>
<div class="page"></div>

<div class="controller">
    <a href="#none" onclick="return false;" class="btn auto">자동시작</a>
    <a href="#none" onclick="return false;" class="btn destroy">삭제</a>
    <a href="#none" onclick="return false;" class="btn init">초기화</a>
</div>


<style>
.container {width: 600px;height: 300px;margin:0 auto;border:solid 1px #333; overflow: hidden; position: relative;}  
.container .pn{ position: absolute; z-index: 10; height:100%; display:flex;justify-content:center; align-items: center; width:50px;}
.container .pn.prev{ left:0;}
.container .pn.next{ right:0;}
.container .pn a.btn{ text-decoration: none; font-size:21px; font-weight:900; padding:8px 0; color:#333;}
.container .api-swiper .swiper-wrapper .swiper-slide{ width:100%; height:100%; position: relative;display:flex;justify-content:center; align-items: center;}

.page {width: 600px;margin:15px auto; overflow: hidden; text-align: center;}  
.page a.btn{text-decoration: none; color:#333; margin:0 5px; display:inline-block; width:20px; text-align:center;}
.page a.btn.active{ color:#f00; font-weight:900; }

.controller{width: 600px;margin:30px auto; overflow: hidden; text-align: center;}
.controller a.btn{ display:inline-block;text-decoration: none; font-size:14px; font-weight:900;color:#333; margin:0 9px; padding:5px 3px; border:solid 1px #333; text-align:center;}
</style>

<script>
var obj = {
    swiper : false,

    // 옵션변수 
    option:{
        // swiepr 기본옵션
        default: {
            direction: 'horizontal',
            loop: true,         
            speed: 500,   
            autoplay:{
                delay: 1000,
            }
        },

        // 사용자 정의 옵션
        customer :{
            pageActiveClass:'active',
        }
    },

    // 캐시변수
    cache:{
        realIndex : 0,
        autoplay : false,
    },

    // 로드
    load :function(){

        // 비우기
        obj.destroy();

        // 삭제 이벤트
        $(document).on('click','.destroy',function(){ obj.destroy();});

        // 초기화 이벤트
        $(document).on('click','.init',function(){ obj.load();});

        // 이벤트 로드
        obj.event();
    },

    // 이벤트
    event: function(){

        // 페이지 생성 
        var $page = $('.page');
        $page.html('');
        $('.swiper-slide').each(function(i){
            $page.append('<a href="#none" onclick="return false;" class="btn" data-index="'+i+'">'+(i+1)+'</a>');
        });
        $page.find('a').on('click',function(){
            obj.swiper.slideTo($(this).data('index'),obj.option.default.speed);
        });        
        $page.find('a').eq(0).addClass(obj.option.customer.pageActiveClass); // 페이지 첫번째는 active

        // 스와이퍼 로드
        obj.swiper = new Swiper('.api-swiper', obj.option.default);  
        obj.swiper.autoplay.stop();

        // 변경이벤트
        obj.swiper.on('slideChange',function(){
            obj.cache.realIndex = obj.swiper.realIndex;
            $page.find('a').removeClass(obj.option.customer.pageActiveClass);
            $page.find('a[data-index="'+(obj.swiper.realIndex)+'"]').addClass(obj.option.customer.pageActiveClass);
        });


        // 이전/다음 버튼 이벤트 
        $('.prev').on('click',function(){ obj.swiper.slidePrev(obj.option.default.speed); });
        $('.next').on('click',function(){ obj.swiper.slideNext(obj.option.default.speed); });

        // 자동시작/중지 이벤트 
        $('.auto').on('click',function(){
            var active = $(this).hasClass('active');
            if( active == true){
                $(this).removeClass('active').text('자동시작');
                obj.swiper.autoplay.stop();
                obj.cache.autoplay = false;
            }
            else{
                $(this).addClass('active').text('일시중지');
                obj.swiper.autoplay.start();
                obj.cache.autoplay = true;
            }
        });        
    },

    // 삭제
    destroy : function(){
        //  체크
        if( typeof obj.swiper != 'object'){ return false; }

        // 비우기        
        obj.swiper.destroy();
        $('.page').html('');        
        $('.prev,.next,.auto').off('click');
        $('.auto').removeClass('active').text('자동시작');
    }
}
obj.load();
</script>

 

결과|

 

결과 화면을 보면 이전/다음 버튼이 슬라이드 양쪽에 추가 되었고, 바로 하단에는 페이지 버튼이 스크립트에 의해 자동생성되도록 구성되어있다. 또한 맨 하단에는 컨트롤러인 자동시작, 삭제, 초기화 버튼등으로 구성되어있다. 

 

이번편은 Swiper API를 실무에서 사용하기 위한 가장 기초적인 구성에 대해 알아보았고 다음편에서는 이를 활용하여 좀더 고급화된 기능에 대해 알아보도록 하자.

이 포스트글이 도움이 되었나요?
2
그룹 목록
카테고리 연관글

Comment

댓글작성

0(500) | 1(30)