Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript와 CSS만으로 드래그 가능한 HTML 요소 만들기

웹 페이지에서 요소를 마우스로 끌어다 놓을 수 있게 하려면 복잡한 라이브러리가 필요하지 않습니다. 순수 JavaScript와 CSS만으로도 충분히 구현할 수 있습니다. 핵심은 마우스 이벤트(mousedown, mousemove, mouseup)를 활용해 요소의 좌표를 실시간으로 갱신하는 것입니다.

전체 예제 코드

<!DOCTYPE html>
<html>
<style>
    body {
        font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }
    .dragDiv {
        position: absolute;
        z-index: 9;
        text-align: center;
        border: 1px solid #d3d3d3;
        padding: 30px;
        cursor: move;
        z-index: 10;
        background-color: rgb(108, 24, 177);
        color: #fff;
        font-size: 20px;
        font-weight: 500;
    }
</style>
<body>
<h1>Draggable DIV Element Example</h1>
<h2>Click and drag the below element to move it around</h2>
<div class="dragDiv">
This div can be moved around
</div>
<script>
    dragElement(document.querySelector(".dragDiv"));
    function dragElement(ele) {
        var pos1 = 0,
        pos2 = 0,
        pos3 = 0,
        pos4 = 0;
        if (document.querySelector(ele.id + "header")) {
            document.getElementById(
                ele.id + "header"
            ).onmousedown = dragMouseDown;
        }
        else {
            ele.onmousedown = dragMouseDown;
        }
        function dragMouseDown(e) {
            e = e || window.event;
            e.preventDefault();
            pos3 = e.clientX;
            pos4 = e.clientY;
            document.onmouseup = closeDragElement;
            document.onmousemove = elementDrag;
        }
        function elementDrag(e) {
            e = e || window.event;
            e.preventDefault();
            pos1 = pos3 - e.clientX;
            pos2 = pos4 - e.clientY;
            pos3 = e.clientX;
            pos4 = e.clientY;
            ele.style.top = ele.offsetTop - pos2 + "px";
            ele.style.left = ele.offsetLeft - pos1 + "px";
        }
        function closeDragElement() {
            document.onmouseup = null;
            document.onmousemove = null;
        }
    }
</script>
</body>
</html>

코드 동작 원리

  • CSS 설정: 대상 요소에 position: absolute;를 지정해야 top, left 값으로 자유롭게 위치를 조절할 수 있습니다. 또한 cursor: move;를 적용하면 사용자에게 드래그 가능함을 시각적으로 알려줄 수 있습니다.
  • dragMouseDown: 마우스 버튼을 누르는 순간 현재 커서 좌표(clientX, clientY)를 저장하고, 문서 전체에 mousemove와 mouseup 이벤트 리스너를 등록합니다.
  • elementDrag: 마우스가 이동할 때마다 이전 좌표와 현재 좌표의 차이를 계산하여 요소의 topleft 값을 업데이트합니다. 이 차이 계산 방식이 부드러운 드래그 경험의 핵심입니다.
  • closeDragElement: 마우스 버튼을 놓으면 등록된 이벤트 리스너를 제거하여 드래그를 종료합니다.

실행 결과

위 코드를 브라우저에서 실행하면 다음과 같은 화면이 나타납니다.

JavaScript와 CSS만으로 드래그 가능한 HTML 요소 만들기

보라색 DIV를 마우스로 클릭한 상태에서 끌어 이동시키면, 요소가 커서를 따라 움직이며 위치가 변경됩니다.

JavaScript와 CSS만으로 드래그 가능한 HTML 요소 만들기

마무리

이 방식은 모달 창, 이미지 갤러리, 칸반 보드 카드 등 다양한 UI에서 응용할 수 있습니다. 터치 기기까지 지원하려면 touchstart, touchmove, touchend 이벤트를 추가로 처리하면 됩니다.