본문 바로가기
웹개발/JavaScript

[자바스크립트] 스와이프 기능과 터치

by 철없는민물장어 2023. 2. 6.
728x90
var 시작좌표 = 0;
        var 눌렀음 = false;


        $('.slide-box').on('mousedown', function(e) {
            시작좌표 = e.clientX;
            눌렀음 = true;
        });
        $('.slide-box').on('mousemove', function(e) {
            if (눌렀음 == true) {
                $('.slide-container').css('transform', `translateX(${e.clientX - 시작좌표}px -${지금사진}00vw)`);

            }

        });
        $('.slide-box').on('mouseup', function(e) {
            눌렀음 = false;
            console.log(e.clientX - 시작좌표);
            if (e.clientX - 시작좌표 < -100) {
                $('.slide-container').css('transform', 'translateX(-100vw)').css('transition', 'all 0.5s');

            } else {
                $('.slide-container').css('transform', 'translateX(0vw)').css('transition', 'all 0.5s');
            
            
            }

            setTimeout(function() {
                $('.slide-container').css('transition', 'none');
            }, 500);
        });

mousedown

mouseup

mousemove 이벤트리스너를 사용하면 된다.

 

mousedown시 마우스 좌표를 '시작좌표'에 저장해두고,

추후 드래그를 구현하기 위해 

let 눌렀음 = true 를 저장해둔다.

 

mousemove는 사진 위에서 마우스가 움직이는것을 감지하는데,

만약 눌렀음==true인 경우에는 드래그를 하는것으로 간주,

사진을 transform: translateX()를 이용하여 움직이면 된다.

움직이는 크기는 (현재좌표 - 시작좌표)로 하면 알맞게 된다.

(그럼 시작좌표보다 왼쪽으로 가면 마이너스값이 나와서 왼쪽으로 사진을 옮길 수 있다)

 

mouseup시에는 변수 눌렀음= false로 변경해 준다.

그리고 사진이 움직인 크기(현재좌표-시작좌표) 값을 보고

100이상 움직였다면 다음 사진을,

아니라면 원래대로 사진이 보이게 translateX()를 조정해 주면 된다.

 

 

이 이벤트들은 mouse이벤트이기 때문에,

모바일에서는 작동하지 않는다.

 

모바일에서 적용되게 하기위해서는 

touchstart

touchmove

touchend

이벤트리스너를 사용해야 한다.

/*터치*/
        $('.slide-box').on('touchstart', function(e) {
            시작좌표 = e.touches[0].clientX;
            눌렀음 = true;
        });
        $('.slide-box').on('touchmove', function(e) {
            if (눌렀음 == true) {
                $('.slide-container').css('transform', `translateX(${e.touches[0].clientX - 시작좌표}px)`);
                
                지금사진 = (지금사진 + 1) % 3;
            $('.slide-container').css('transform', 'translateX(-' + 지금사진 + '00vw)');
            }

        });
        $('.slide-box').eq(0).on('touchend', function(e) {
            눌렀음 = false;
            if (e.changedTouches[0].clientX - 시작좌표 < -100) {
                $('.slide-container').css('transform', 'translateX(-100vw)').css('transition', 'all 0.5s');
            } else {
                $('.slide-container').css('transform', 'translateX(0vw)').css('transition', 'all 0.5s');
            }

            setTimeout(function() {
                $('.slide-container').css('transition', 'none');
            }, 500);
        });

또한 현재좌표를 event.clientX가 아니라event.touches[0].clientX를 사용해야하고,

touchend시에는 event.changedTouches[0].clientX를 사용해야한다.

 

이렇게 스와이프를 마우스,터치로 구현할 수 있는데

코드도 너무 복잡하고 길기 때문에

보통은 hammer.js를 사용하여 구현한다고 하니 참고하자.

 

728x90

댓글