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

jQuery로 컨테이너 div 안에서 이미지 드래그·패닝 구현하기

mousedown, mouseup, mousemove 같은 마우스 이벤트를 활용하면 컨테이너 div 안의 이미지를 자유롭게 이동(translate)시켜 드래그 효과를 구현할 수 있습니다. 마우스 버튼을 누르는 순간 좌표를 기록하고, 마우스가 움직일 때마다 그 차이만큼 이미지 위치를 갱신한 뒤, 버튼을 떼면 이벤트를 해제하는 방식입니다.

동작 원리

드래그 기능은 크게 세 단계로 나눌 수 있습니다.

1. mousedown: 드래그를 시작하는 시점의 마우스 좌표(pageX, pageY)에서 현재 이미지의 이동 거리(disp)를 뺀 값을 시작 위치로 저장합니다.

2. mousemove: 문서 전체에 바인딩된 mousemove 이벤트에서 현재 마우스 좌표에서 시작 위치를 빼 새로운 이동 거리를 계산하고, CSS transform: translate() 속성으로 이미지를 실제로 움직입니다.

3. mouseup: 마우스 버튼을 떼면 mousemove 이벤트를 off() 메서드로 제거해 드래그를 종료합니다.

예제 코드

다음 예제는 jQuery를 사용해 부모 div(#parent) 안의 이미지(#mover)를 드래그로 이동시키는 방법을 보여줍니다.

<!DOCTYPE html>
<html>
<head>
<style>
#parent{
    position: absolute;
    margin: 20px;
    width: 200px;
    height: 200px;
    border-radius: 25px;
    background-color: khaki;
}
#mover {
    position: relative;
    margin: 10px;
}
</style>
</head>
<body>
<div id=parent>
<img id="mover" src="https://images.unsplash.com/photo-1613333238609-
ef9218f3ddbd?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=100&ixlib=rb1.2.1&q=80&w=100" />
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
let ele = {startPositionX:0,startPositionY:0};
let disp = {x:0,y:0};
$('#parent').on("mousedown",function(e){
    let container = $(this);
    ele.startPositionX=e.pageX-disp.x;
    ele.startPositionY=e.pageY-disp.y;
    $(document).on("mousemove",function(e){
        disp.x=e.pageX-ele.startPositionX;
        disp.y=e.pageY-ele.startPositionY;
        $('#mover').css('transform','scale('+1.0+') translate('+disp.x+'px, '+disp.y+'px)');
    });
});
$(document).on("mouseup",function(){
    $(this).off("mousemove");
});
</script>
</body>
</html>

코드 설명

  • #parent 스타일: 200×200 크기의 카키색 배경 컨테이너로, position: absolute로 배치되어 드래그 영역을 시각적으로 보여줍니다.
  • #mover 스타일: 이동 대상인 이미지에 position: relative를 적용해 transform으로 위치를 조정할 수 있게 합니다.
  • ele 객체: 드래그 시작 시점의 기준 좌표(startPositionX, startPositionY)를 저장합니다.
  • disp 객체: 현재까지 이미지가 이동한 x, y 거리를 추적합니다. 덕분에 드래그를 반복해도 이미지가 원점으로 튀지 않고 이전 위치에서 자연스럽게 이어집니다.
  • transform 적용: scale(1.0)과 translate()를 함께 사용해 확대 없이 순수하게 위치만 이동시킵니다.

실행 결과

위 코드를 실행하면 다음과 같은 결과가 나타납니다.

jQuery로 컨테이너 div 안에서 이미지 드래그·패닝 구현하기

드래그 중

jQuery로 컨테이너 div 안에서 이미지 드래그·패닝 구현하기

마우스로 컨테이너를 클릭한 상태에서 움직이면 이미지가 함께 따라오고, 마우스 버튼을 떼면 이동이 멈춥니다. 이 방식은 지도 뷰어, 이미지 갤러리, 캔버스형 UI 등 다양한 인터랙티브 요소에 응용할 수 있습니다.