본문 바로가기
Front-end/애니메이션

터치스크린 인터페이스에서의 인터랙션 최적화

by mooyou 2025. 3. 22.
728x90
300x250
SMALL

 

모바일 환경에서 터치스크린 인터페이스를 활용하여, 터치 이벤트에 반응하는 UI를 최적화하는 방법을 알아보자 이를 통해 사용자가 스와이프나 탭 등의 제스처로 직관적으로 조작할 수 있는 UI를 만들 수 있다.

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>터치스크린 인터페이스</title>
  <style>
    .carousel {
      display: flex;
      overflow: hidden;
      width: 300px;
      margin: auto;
    }
    .carousel-item {
      min-width: 300px;
      transition: transform 0.3s ease;
    }
  </style>
</head>
<body>
  <div class="carousel">
    <div class="carousel-item" style="background-color: #3498db;">Item 1</div>
    <div class="carousel-item" style="background-color: #2ecc71;">Item 2</div>
    <div class="carousel-item" style="background-color: #e74c3c;">Item 3</div>
  </div>

  <script>
    let startX = 0;
    let currentTranslate = 0;

    const carousel = document.querySelector('.carousel');
    carousel.addEventListener('touchstart', (e) => {
      startX = e.touches[0].clientX;
    });

    carousel.addEventListener('touchmove', (e) => {
      const moveX = e.touches[0].clientX;
      const diff = startX - moveX;
      carousel.style.transform = `translateX(${currentTranslate - diff}px)`;
    });

    carousel.addEventListener('touchend', () => {
      currentTranslate = parseInt(carousel.style.transform.replace('translateX(', '').replace('px)', ''), 10);
    });
  </script>
</body>
</html>

 

코드 설명

  • 위 코드는 스와이프 제스처를 사용하여, 터치스크린 환경에서 수평 슬라이드 효과를 구현한 예제로 모바일 기기에서 사용자가 스와이프를 할 때 슬라이드 형태로 이동하는 캐러셀을 만드는 방법을 설명한다.
  • touchstart, touchmove, touchend 이벤트를 사용하여 터치 이벤트를 감지하고, 스와이프에 따라 carousel을 이동시킨다.
  • touchstart : 사용자가 화면을 터치했을 때 발생하는이벤트이다. 이 때 e.touches[0].clientX를 통해 터치가 시작된 x좌표를 가져온다.
  • touchmove : 사용자가 터치한 상태에서 손가락을 이동시킬 때 발생하는 이벤트이다. e.touches[0].clientx를 통해 손가락의 현재 위치를 알 수 있ㄷ. startX와 비교하여 움직인 거리를 계산하고, 이 값을 바탕으로 캐러셀의 transform 속성을 조정하여 슬라이드 위치를 변경한다.
  • touchend : 손가락을 화면에서 떼면 발생하는 이벤트이다. 현재 위치를 currentranslate에 저장하여, 이후 스와이프 이동을 게속 추적할 수 있게 한다.
  • transform:translatex(100px)로 요소를 수평방향으로 100px만큼 이동 시킨다.
  • carousel.style.transform=translateX(${currentTranslate - diff}px);는 스와이프한 이동거리를 실시간으로 반영해 캐러
  • 셀의 위치를 변경한다.

 

전체 동작 과정

  1. touchstart에서 사용자가 화면을 터치하면, 터치가 시작된 x좌표를 기록한다.
  2. touchmove에서 손가락을 이동시키면, 이동한 거리(차이값)를 계산하고, 이를 이용해 캐러셀의 위치를 조정한다.
  3. touchend에서 손가락을 떼면, 현재 이동한 거리(currentTranslate)를 저장해두고, 다음에 스와이프를 시작할 때 그 값을 기준으로 이동할 수 있게 한다.

 

야 초보자용으로 쓰는건데 이거 설명이 너무 대충인거 아니야? window.addEventListener('scroll', () => { const sections = document.querySelectorAll('.section'); sections.forEach(section => { const rect = section.getBoundingClientRect(); if (rect.top >= 0 && rect.top <= window.innerHeight) { section.classList.add('visible'); } else { section.classList.remove('visible'); } }); }); 좀더 자세히 해줘야지 addEventListener 이게 뭔지 getBoundingClientRect() 이게 뭔지 어떻게 알음? 아래도 마찬가지임 설명을 좀 자세히 해줘야지
728x90
반응형
LIST

댓글