마우스로 DIV 나 이미지를 끌어서 움직이는 소스
<html>
<head>
</head>
<body>
<script type='text/javascript'>
var img_L = 0;
var img_T = 0;
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>
</body>
<div style='position:absolute; left:0px; top:0px; cursor:pointer; cursor:hand' onmousedown='startDrag(event, this)'>
<table bgcolor="#0000FF"><tr><td>
<font color="#FFFFFF">하하하</font>
</td></tr></table>
</div>
<img src="http://www.horangi.kr/miniapp/doumi/img/ttokki.gif"
width="150" style="position:absolute; left:0px; top:50px;
cursor:pointer; cursor:hand" onmousedown="startDrag(event, this)"
border="0">
</html>
|
움직이려는 오브젝트의 style 속성에
position:absolute 와
left:
top:
속성을 반드시 지정해 주어야 함.