images.zip



#img1을 #bar의 영역에서 계속 좌우로 움직이도록 만들어주세요.


<!DOCTYPE html PUBLIC "-//W3C//DTD Xhtml 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<style>
body {
font-size: 9pt;
}
#panel {
width: 600px;
height: 300px;
border: 1px solid #999;
position: relative;
}
#bar {
position: absolute;
left: 50px;
top: 190px;
width: 500px;
height: 20px;
background: #F30;
}
#img1 {
position: absolute;
left: 50px;
top: 70px;
}
#nav {
text-align: center;
width: 600px;
}
</style>
<script>
window.onload=function(){
this.initEventListener();
}
function initEventListener(){
var img1 = document.getElementById('img1');
var nowLeft = img1.offsetLeft; //초기 이미지 위치
var endLeft;
var moveLeft = 0; //움직이는 동안의 이미지 위치
var speed = 2; //속도
var chk=0; //앞으로 갈지, 뒤로 갈지 체크하는 변수
var goTimer; //setInterval을 정지시키기 위해서 사용하는 변수
var btnStart = document.getElementById("btn_start").addEventListener("click",function(){
clearInterval(goTimer);
start();
},false);
var btnStop = document.getElementById("btn_stop").addEventListener("click",function(){
clearInterval(goTimer);
},false);
function start(){
//clearInterval을 사용하기 위해서 goTimer가 setInterval을 참조한다.
//참조하는 동시에 setInterval(moveImg, 10) 실행!!!
goTimer = setInterval(moveImg, 10);
}
function moveImg(){
if(chk == 0){ // chk가 0이면 앞으로 += 하며 출발!!!
nowLeft += speed; //속도인 speed를 2로 지정했었지요...
moveLeft = nowLeft + "px";
if(nowLeft > 430){ //좌표 430까지 가면 chk=1로 하여 뒤로 돌아가기 위한 조건을 준다.
chk = 1;
}
}
if(chk == 1){ // chk가 1이면 뒤로 -= 하며 출발!!!
nowLeft -= speed; //뒤로 -하며 돌아가겠지요?
moveLeft = nowLeft + "px";
if(nowLeft == 50){ //첫 위치인 50에 도착하면 chk=0 으로 하여 앞으로 가기 위한 조건을 준다.
chk = 0;
}
}
img1.style.left = moveLeft;
}
}
</script>
</head>
<body>
<div>
<h4>#img1을 #bar의 영역에서 계속 좌우로 움직이도록 만들어주세요.</h4>
<div id="panel">
<div id="bar"></div>
<div id="img1">
<img src="images/img1.jpg">
</div>
</div>
<div id="nav">
<button id="btn_start">시작</button>
<button id="btn_stop">멈춤</button>
</div>
</div>
</body>
</html>


+ Recent posts