PC 수평 스크롤 터치 (클릭 드래그)

Eddy·2023년 3월 1일
1

Javascript

목록 보기
9/27
<div class="select_size_area">
  <div class="size">전체</div>
  <div class="size">230</div>
  <div class="size">235</div>
  <div class="size">240</div>
  <div class="size">245</div>
  <div class="size">250</div>
  <div class="size">255</div>
  <div class="size">260</div>
  <div class="size">265</div>
  <div class="size">270</div>
  <div class="size">275</div>
  <div class="size">280</div>
</div>
<script>
  const slider = document.querySelector('.select_size_area');
  let isDown = false;
  let startX;
  let scrollLeft;

  slider.addEventListener('mousedown', e => {
    isDown = true;
    slider.classList.add('active');
    startX = e.pageX - slider.offsetLeft;
    scrollLeft = slider.scrollLeft;
  });

  slider.addEventListener('mouseleave', () => {
    isDown = false;
    slider.classList.remove('active');
  });

  slider.addEventListener('mouseup', () => {
    isDown = false;
    slider.classList.remove('active');
  });

  slider.addEventListener('mousemove', e => {
    if (!isDown) return; 
    e.preventDefault();
    const x = e.pageX - slider.offsetLeft;
    const walk = x - startX;
    slider.scrollLeft = scrollLeft - walk;
  });
</script>

Jqaury로 수정한 버전

 bindSlideTabs() {
    const slider = $('.select_size_area');

    let x, left, down;

    slider.mousedown(function (e) {
      e.preventDefault();
      down = true;
      x = e.pageX;
      left = $(this).scrollLeft();
    });

    slider.mousemove(function (e) {
      if (down) {
        var newX = e.pageX;
        $(this).scrollLeft(left - newX + x);
      }
    });

    slider.mouseleave(function (e) {
      down = false;
    });

    slider.mouseup(function (e) {
      down = false;
    });
  }

0개의 댓글