본문 바로가기
Frontend/JavaScript

18. JavaScript 연습문제 (이미지스크롤)

by 개발개발빈이 2022. 5. 11.

● 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>

완성화면 캡처
balloon_red.png
balloon_yellow.png
balloon_green.png
balloon_blue.png

댓글