프로그램/script

html and javascript mouse move capture and drag

mulderu 2010. 8. 18. 13:42
javascript를 이용한 mouse 핸들링의 좋은 예라고 생각 합니다.
출처 : http://www.webreference.com/programming/javascript/mk/column2/


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> Mouse Move Capture And Drag Demo </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">

<style type="text/stylesheet">
</style>

<SCRIPT LANGUAGE="JavaScript">
<!--


var dragObject  = null;
var mouseOffset = null;

function getMouseOffset(target, ev){
ev = ev || window.event;

var docPos    = getPosition(target);
var mousePos  = mouseCoords(ev);
return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function getPosition(e){
var left = 0;
var top  = 0;

while (e.offsetParent){
left += e.offsetLeft;
top  += e.offsetTop;
e     = e.offsetParent;
}

left += e.offsetLeft;
top  += e.offsetTop;

return {x:left, y:top};
}

function mouseCoords(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop  - document.body.clientTop
};
}

function mouseMove(ev){
ev           = ev || window.event;
var mousePos = mouseCoords(ev);

if(dragObject){
dragObject.style.position = 'absolute';
//dragObject.style.top      = mousePos.y - mouseOffset.y;
dragObject.style.left     = mousePos.x - mouseOffset.x;

return false;
}
}
function mouseUp(){
dragObject = null;
}

function makeDraggable(item){
if(!item) return;
item.onmousedown = function(ev){
dragObject  = this;
mouseOffset = getMouseOffset(this, ev);
return false;
}
}

function onloadok() {
document.getElementById("div1").onmousemove = mouseMove;
document.getElementById("div1").onmouseup   = mouseUp;

makeDraggable(document.getElementById("div1"));
}
//-->
</SCRIPT>
</HEAD>

<BODY onload="onloadok()">

<div id="pre">
<p>aaaaaaaaaaa</p>
<p>aaaaaaaaaaa</p>
<p>aaaaaaaaaaa</p>
</div>

<DIV NAME="div1" id="div1">
<IMG SRC="http://www.bloter.net/files/2010/08/android2.jpg"/>
</DIV>

<div id="after">
<p>xxxxxxxxxxxxx</p>
<p>xxxxxxxxxxxxx</p>
<p>xxxxxxxxxxxxx</p>
</div>

</BODY>
</HTML>