본문 바로가기

프로그래밍언어/Javascript

JavaScript 이미지를 드래그하여 움직이기!

<script type='text/javascript'>
//처음 이미지가 생성될곳을 지정해 줍니다
var img_L = 10;
var img_T = 20;
var targetObj;

function getLeft(o){
     return parseInt(o.style.left.replace('px', ''));
}
function getTop(o){
     return parseInt(o.style.top.replace('px', ''));
}

// 이미지를 움직이는 함수입니다 움직였던 위치만큼 처음 이미지가 있던 좌표를 더해줍니다 최종 위치입니다
function moveDrag(e){
     var e_obj = window.event? window.event : e;
     var dmvx = parseInt(e_obj.clientX + img_L);
     var dmvy = parseInt(e_obj.clientY + img_T);
     targetObj.style.left = dmvx +"px";
     targetObj.style.top = dmvy +"px";
     return false;
}

// 드래그를 시작하는 함수 입니다. 움직였던 좌표에서 처음 드래그를 시작했던 좌표를 빼줍니다. 움직인 좌표를 나타내줍니다
function startDrag(e, obj){
     targetObj = obj;
     var e_obj = window.event? window.event : e;
     img_L = getLeft(obj) - e_obj.clientX;
     img_T = getTop(obj) - e_obj.clientY;

     document.onmousemove = moveDrag;
     document.onmouseup = stopDrag;
     if(e_obj.preventDefault)e_obj.preventDefault(); 
}

// 드래그를 멈추는 함수 입니다
function stopDrag(){
     document.onmousemove = null;
     document.onmouseup = null;
}
</script>

<img src="4.png" style="position:absolute; left:0px; top:50px; cursor:pointer; cursor:hand; border:0" onmousedown="startDrag(event, this)">
//마우스를 이미지에 클릭하면 startDrag의 함수가 시작 됩니다