1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| <script> // 상태 관리 함수 const createDragState = () => ({ isPressed: false, startX: 0, startY: 0, scrollLeft: 0, scrollTop: 0, });
// 커서 스타일 설정 함수 const setCursor = (element, cursor) => { element.style.cursor = cursor; };
// 좌표 추출 함수 (마우스/터치 통합) const getEventCoordinates = (e) => { if (e.touches && e.touches.length > 0) { return { pageX: e.touches[0].pageX, pageY: e.touches[0].pageY }; } return { pageX: e.pageX, pageY: e.pageY }; };
// 시작 핸들러 (마우스다운/터치스타트) const handleStart = (state) => (e) => { state.isPressed = true; setCursor(e.currentTarget, "grabbing");
const coords = getEventCoordinates(e); state.startX = coords.pageX - e.currentTarget.offsetLeft; state.scrollLeft = e.currentTarget.scrollLeft; state.startY = coords.pageY - e.currentTarget.offsetTop; state.scrollTop = e.currentTarget.scrollTop;
// 터치 이벤트는 preventDefault 호출 if (e.type === "touchstart") { e.preventDefault(); } };
// 마우스 엔터 핸들러 const handleMouseEnter = (e) => { setCursor(e.currentTarget, "grab"); };
// 종료 핸들러 (마우스업/터치엔드/마우스리브) const handleEnd = (state) => (e) => { state.isPressed = false; setCursor(e.currentTarget, "grab"); };
// 이동 핸들러 (마우스무브/터치무브) const handleMove = (state, speed = 2) => (e) => { if (!state.isPressed) return; e.preventDefault();
const container = e.currentTarget; const coords = getEventCoordinates(e);
const x = coords.pageX - container.offsetLeft; const walkX = (x - state.startX) * speed; container.scrollLeft = state.scrollLeft - walkX;
const y = coords.pageY - container.offsetTop; const walkY = (y - state.startY) * speed; container.scrollTop = state.scrollTop - walkY; };
// 이벤트 리스너 바인딩 함수 const bindEventListeners = (container, state, speed) => { // 마우스 이벤트 container.addEventListener("mousedown", handleStart(state)); container.addEventListener("mouseenter", handleMouseEnter); container.addEventListener("mouseleave", handleEnd(state)); container.addEventListener("mouseup", handleEnd(state)); container.addEventListener("mousemove", handleMove(state, speed));
// 터치 이벤트 container.addEventListener("touchstart", handleStart(state), { passive: false, }); container.addEventListener("touchend", handleEnd(state)); container.addEventListener("touchmove", handleMove(state, speed), { passive: false, });
// 텍스트 선택 방지 container.addEventListener("selectstart", (e) => e.preventDefault()); };
// 드래그 스크롤 초기화 함수 const initDragScroll = (selector, speed = 2) => { const container = document.querySelector(selector); if (!container) return;
const state = createDragState(); bindEventListeners(container, state, speed);
return state; };
// 초기화 const scrollState = initDragScroll("#scroll-container", 2); </script>
|