● PRACTICE 연습문제
Q1) 풍선 이미지 스크롤 (자바스크립트 총정리)
- 4개의 풍선이미지가 왼쪽으로 이동하도록
<head>
<meta charset="UTF-8">
<title>imageScroll</title>
<style>
#mydiv{
position: relative;
left: 100px;
top: 10px;
width: 285px;
height: 120px;
background-color: white;
overflow: hidden; /* 8) 영역 밖의 내용은 숨기기 */
}
</style>
<script>
// 1) 스크롤하고자 하는 이미지를 전역변수에 저장
var ctnt=[];
ctnt[0]="<img src='../image/balloon_red.png' width='85'>";
ctnt[1]="<img src='../image/balloon_yellow.png' width='85'>";
ctnt[2]="<img src='../image/balloon_green.png' width='85'>";
ctnt[3]="<img src='../image/balloon_blue.png' width='85'>";
ctnt[4]="<img src='../image/balloon_red.png' width='85'>";
ctnt[5]="<img src='../image/balloon_yellow.png' width='85'>";
ctnt[6]="<img src='../image/balloon_green.png' width='85'>";
ctnt[7]="<img src='../image/balloon_blue.png' width='85'>";
var size=ctnt.length
// 2) 1)에서 준비한 이미지를 id=mydiv에 배치하기
function start(){
for(i=0; i<size; i++){
document.write("<div id='area" + i + "' style='position:absolute; top:0; left:" + i*95 + "px;'>");
document.write(ctnt[i]);
document.write("</div>");
}//for end
}//start() end
// 3) 3초후에 scroll함수를 1번호출
setTimeout(scroll, 3000);
// 4) 이미지스크롤
function scroll(){
// 5) id=area0의 스타일을 가져와서 인쪽여백값을 -10px만큼 줄이기
/*
var tmp=document.getElementById("area0").style;
tmp.left = parseInt(tmp.left)-10 + "px";
*/
// id=area0 ~ area7까지 가져와서 인쪽여백값을 -10px만큼 줄이기
for(i=0; i<size; i++){
var tmp=document.getElementById("area" + i).style;
tmp.left = parseInt(tmp.left)-10 + "px";
// 7) 이미지를 순환시키기 위해서 이미지를 다시 배치
if(i%2==0 && parseInt(tmp.left)<=-90){
tmp.left = ((size-1)*95+5) + "px";
}else if(i%2!=0 && parseInt(tmp.left)<=-90){
tmp.left = (size-1)*95 + "px";
}//if end
}//for end
// 6) 0.5초 후 scroll함수 호출
timer = setTimeout(scroll, 500);
} //scroll() end
// 9) 6)의 시간을 해제
var timer; //전역변수
function killtime(){
clearTimeout(timer);
}//killtime() end
</script>
</head>
<body onunload="killtime()"> <!-- 10) 현재 문서에서 나갔거나 종료했을 때 발생하는 이벤트 -->
<h3>이미지스크롤</h3>
<!-- 이미지가 스크롤 되는 위치 -->
<div id="mydiv">
<script>start();</script>
</div>
</body>
'Frontend > JavaScript' 카테고리의 다른 글
20. JavaScript, this (0) | 2022.06.20 |
---|---|
19. JSON (JSON 기본구조, XML, JSON 관련함수) (0) | 2022.06.19 |
17. JavaScript 이벤트(Event) (0) | 2022.05.10 |
16. JavaScript 내장객체 (0) | 2022.05.06 |
15. JavaScript Date 객체 (디지털 시계 만들기) (0) | 2022.05.04 |
댓글