본문 바로가기

javascript

자바스크립트 기본 예제(마우를 클릭드래그하여 오브젝트 이동 시키기)

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

<style type="text/css">

#pop{ width: 100px; height: 100px; position: absolute; left: 100px; top: 100px; border: 1px solid #000000; background: #00FF00; z-index: 200;}

/* #은 #다음에 오는 id를 가진 객체만 사용 가능한 스타일*/

</style>

<script type="text/javascript">

var mx, my;

var on=0;

function move_onoff(e,chk){

var pop=document.getElementById("pop");

// offsetLeft,offsetTop : 부모요소를 기준한 좌표지점.

mx=e.clientX-pop.offsetLeft;

my=e.clientY-pop.offsetTop;

on=chk;

}

function move(e){

if(on==0)

return;

var pop=document.getElementById("pop");

var x=e.clientX-mx;

var y=e.clientY-my;


if(x>0)

pop.style.left=x+"px";

if(y>0)

pop.style.top=y+"px";

}

</script>

</head>

<body>

<div id="pop" onmousedown="move_onoff(event,1);" onmouseup="move_onoff(event,0);" onmousemove="move(event);"></div>

</body>

</html>