Javascript [ 사진 깜빡깜빡 ]

양혜정·2024년 4월 13일
0

HTML/CSS/JS 실행

목록 보기
53/60


HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>숨겼다가 보여주는 슬라이드</title>

<link rel="stylesheet" href="css/slide_hide_show.css">
<script type="text/javascript" src="js/slide_hide_show.js"></script>

</head>
<body>

	<div id="container">
      	<h2 style="text-align: center;">사진을 숨겼다가 보여주는 슬라이드</h2>
	
	  	<div style="display: flex;">
			<!-- 버튼이 가운데 오게 하기 / 그 중 이미지와 가깝게 하기 위해 margin-right:1% 주기 -->
		  	<div style="margin: auto 1% auto auto;">	
		    	<button id="previous"></button>
			</div>	      	
			<div id="images"> 	<!-- 사진들을 배치할 태그이다 -->
				<img src="images/Koala.jpg" />			<!-- img들을 상하로 배치해야 하므로 display 는 block 으로 함 -->
				<img src="images/Lighthouse.jpg" />		<!-- img들을 상하로 배치해야 하므로 display 는 block 으로 함 -->
				<img src="images/Penguins.jpg" />		<!-- img들을 상하로 배치해야 하므로 display 는 block 으로 함 -->
				<img src="images/Tulips.jpg" />			<!-- img들을 상하로 배치해야 하므로 display 는 block 으로 함 -->
			</div>
	      	<div style="margin: auto auto auto 1%;">
	         	<button id="next"></button>
	      	</div>
      	</div>
      
      	<h2 id="msg" style="text-align: center; color: red;"></h2>
      
    </div>

</body>
</html>

JS

window.onload = function(){

    let current_index = 0;      // 현재 인덱스 번호

    const btn_previous = document.querySelector("button#previous");
    const btn_next = document.querySelector("button#next");
    const images = document.querySelectorAll("div#images > img");
    
    // 초기 설정으로 모든 이미지들은 안보이게 만든다.
    images.forEach(elmt => {elmt.style.display = "none";});

    // 초기 설정으로 첫번째 이미지만 보이게 만든다.
    images[0].style.display = "";

/////////////////////////////////////////////////////////////////////////

    // === 이전으로 이동하는 함수 === //
    const func_previous = function(){

        if(current_index > 0){      // 현재 인덱스번호가 처음이 아닌 두번째 이상인 경우
            
            btn_next.removeAttribute('disabled');   // 다음 버튼을 활성화 상태로 만든다.
            // 또는
            // btn_previous.setAttribute('disabled', false);    // 이전 버튼을 활성화 상태로 만든다.
            // 또는
            // btn_previous.disabled = false;   // 이전 버튼을 활성화 상태로 만든다.

            // 초기 설정으로 모든 이미지들은 안보이게 만든다.
            images.forEach(elmt => {elmt.style.display = "none";});

            const img = images[--current_index];
            img.style.display = "";   // 이전 이미지만 보이게 만든다.

        ///////////////////////////////////////////////////////////////////////////////////////
            // === 이미지에 애니메이션 효과 주기(transition) 시작 === //
            img.style.opacity = "0.3";
            // img.style.opacity = "1.0";   ===================> 점점 희미해지기

            let opc = img.style.opacity;
            console.log(`opc : ${opc}`);

            let increase = 0;
            // let del = 0;   // 감소값     ===================> 점점 희미해지기
            const func_img_opacity = setInterval(function(){
                increase += 0.005;
                // del += 0.005;            ===================> 점점 희미해지기
                img.style.opacity = `${Number(opc) + increase}`;
                // img.style.opacity = `${Number(opc) - del}`;  ====> 점점 희미해지기
                // img.style.opacity = `${opc + increase}`; 이 되지않는다. opc 가 string 타입
                // 이 때문에 img.style.opacity = `${Number(opc) + increase}`; 로 해주어야 한다.
                console.log(img.style.opacity);

                if(Number(img.style.opacity) == "1.0"){
                // if(Number(img.style.opacity) == "0.3"){  ========> 점점 희미해지기
                    console.log("그만");
                    console.log("=======================================");
                    clearInterval(func_img_opacity);
                }
            },10);
            // === 이미지에 애니메이션 효과 주기(transition) 끝 === //
        ///////////////////////////////////////////////////////////////////////////////////////

            // 메시지가 안나오게 하기
            document.querySelector("h2#msg").innerHTML = "";

        }
        else{   // 현재 인덱스번호가 처음인 경우
            // 처음 사진일 때 다음버튼을 disabled 로 만든다.
            btn_previous.setAttribute('disabled',true);     // 비활성화
            // 또는
            // btn_previous.disabled = true;                // 비활성화
            document.querySelector("h2#msg").innerHTML = "처음 사진 입니다.";
        }

    }

    // === 다음으로 이동하는 함수 === //
    const func_next = function(){

        if(current_index < 3){      // 현재 인덱스번호가 마지막(지금은 3)이 아닌 경우
            
            btn_previous.removeAttribute('disabled');   // 이전 버튼을 활성화 상태로 만든다.
            // 또는
            // btn_previous.setAttribute('disabled', false);    // 이전 버튼을 활성화 상태로 만든다.
            // 또는
            // btn_previous.disabled = false;   // 이전 버튼을 활성화 상태로 만든다.

            // 초기 설정으로 모든 이미지들은 안보이게 만든다.
            images.forEach(elmt => {elmt.style.display = "none";});

            const img = images[++current_index];
            img.style.display = "";   // 다음번 이미지만 보이게 만든다.

        ///////////////////////////////////////////////////////////////////////////////////////
            // === 이미지에 애니메이션 효과 주기(transition) 시작(점점 진해지기) === //
            img.style.opacity = "0.3";
            // img.style.opacity = "1.0";   ===================> 점점 희미해지기

            let opc = img.style.opacity;
            console.log(`opc : ${opc}`);

            let increase = 0;   // 증가값
            // let del = 0;   // 감소값     ===================> 점점 희미해지기
            const func_img_opacity = setInterval(function(){
                increase += 0.005;
                // del += 0.005;            ===================> 점점 희미해지기
                img.style.opacity = `${Number(opc) + increase}`;
                // img.style.opacity = `${Number(opc) - del}`;  ====> 점점 희미해지기
                // img.style.opacity = `${opc + increase}`; 이 되지않는다. opc 가 string 타입
                // 이 때문에 img.style.opacity = `${Number(opc) + increase}`; 로 해주어야 한다.
                console.log(img.style.opacity);

                if(Number(img.style.opacity) == "1.0"){
                // if(Number(img.style.opacity) == "0.3"){  ========> 점점 희미해지기
                    console.log("그만");
                    console.log("=======================================");
                    clearInterval(func_img_opacity);
                }
            },10);
            // === 이미지에 애니메이션 효과 주기(transition) 끝 === //
        ///////////////////////////////////////////////////////////////////////////////////////


            // 메시지가 안나오게 하기
            document.querySelector("h2#msg").innerHTML = "";

        }
        else{   // 현재 인덱스번호가 마지막(지금은 3)인 경우
            // 마지막 사진일 때 다음버튼을 disabled 로 만든다.
            btn_next.setAttribute('disabled',true);     // 비활성화
            // 또는
            // btn_previous.disabled = true;            // 비활성화
            document.querySelector("h2#msg").innerHTML = "마지막 사진 입니다.";
        }

    }

////////////////////////////////////////////////////////////////////////////////////////////////////

    // 이전 버튼은 초기화로 사용하지 못하도록 disabled 로 만든다.
    btn_previous.setAttribute('disabled', true);    // 비활성화

    // btn_next.addEventListener('click',function(){}); 이 방법도 있지만 함수를 밖으로 꺼낼 수 있다.
    // 이전버튼 클릭시 이전으로 이동하는 함수를 호출한다.
    btn_previous.addEventListener('click',func_previous);
    // 다음버튼 클릭시 다음으로 이동하는 함수를 호출한다.
    btn_next.addEventListener('click',func_next);

}   // end of window.onload = function()------------------------

CSS

@charset "UTF-8";

 div#container {
    border: solid 0px green; 
    width: 70%; 
    margin: 5% auto; /**중앙 정렬한다.**/
 }

 div#images {
    border: solid 0px red;
    width: 900px;   /* 화면상에 보여지는 장소이므로 width 는 img 태그의 width 와 동일하게 설정한다. */
    height: 300px;  /* 화면상에 보여지는 장소이므로 height 는 img 태그의 height 와 동일하게 설정한다. */
    /*overflow: hidden; /* overflow: hidden을 사용하여 width: 900px; 과 height: 300px; 을 넘어서 보여지는 사진들을 안보이도록 만든다. */
  }

 div#images > img {
      display: block;   /* img들을 상하로 배치해야 하므로 display 는 block 으로 함 */
      width: 900px;  /* div#slide 크기와 동일하게 설정한다. */
      height: 300px; /* div#slide 크기와 동일하게 설정한다. */
 }

 
 /* 버튼디자인 */
 button {
   width: 50px; 
   height: 50px;
   background-color: #646464;
   color: white;
   font-size: 20pt;
   border-radius: 50%;
 }

 button:active { /* 버튼을 클릭하는 동안 색을 바꾼다. */
   background-color:#3e3e3e;
 }

 button:disabled { /* 버튼 속성이 disabled되면 색을 바꾼다. */
   background-color: #cbcaca;
 }

정리

  • 10_slide
    -> slide_hide_show.html, slide_hide_show.js, slide_hide_show.css

0개의 댓글

관련 채용 정보