개발 기술/css 애니메이션 (with js)

Traffic Light(신호등) 애니메이션을 만들자

by GicoMomg 2021. 9. 16.

1. 미리보기

border-radius, border-right 혹은 border-left를 이용해 신호등과 신호등에 비치는 불빛을 만들 수 있다! 한 번 만들어보자

See the Pen javascript_day9 by KumJungMin (@kumjungmin) on CodePen.



2. 코드 설명

1) html

<div class="container">               <!--[1]-->
  <div class="circle red" color="red"></div>    <!--[2]-->
  <div class="circle" color="yellow"></div>
  <div class="circle" color="green"></div>
</div>
  • [1] 신호등 원들을 중앙배치하는 부모요소이다.
  • [2] 각각 신호등 원(빨강, 노랑, 초록)에 대한 요소이다.

2) css

  • [3] container 내부 요소들을, flexflex-direction를 사용해 세로 배치시킨다.
    .container {     /*[3]*/
    width: 70px;
    height: 200px;
    border-radius: 50px;
    background-color: #2c3e50;
    display: flex;                  /*important*/
    align-items: center;            /*수직 방향 중앙 배치*/
    justify-content: space-between; /*요소 사이에 공간을 두고 배치*/
    flex-direction: column;        /*세로 정렬*/
    padding: 15px;
    }

  • [4] 신호등 원에 대한 css이다. border-radius:50%를 주면 원을 만들 수 있다.
    .circle {     /*[4]*/
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: rgba(0, 0, 0, 0.3); 
    position: relative;  /*after사용을 위해 relative 설정*/
    }

  • [5]
    : circle에 after를 사용하여, 신호등 원에 빛이 비친 형태를 만들 수 있다.
    : 아래 사진은 빛 비친 모양을 만드는 모습이다.
    : 먼저, border-right를 사용해 border의 한 부분에만 solid 값을 준다.
    : 그 다음, border-radius:50%를 사용해 초승달 모양을 만들 수 있다.

.circle::after {
  border-right: 4px solid rgba(255, 255, 255, 0.6);  /*한부분만 solid 적용*/
  content: '';
  width: 30px;
  height: 30px;
  border-radius: 50%;    /* 초승달 모양 만들기 */
  position: absolute;
  top: 5px;
}

  • [6]
    : 신호등 별로 색깔을 지정하는 class를 생성한다.
    :.class1.class2처럼 두 개의 class를 붙여서 사용하면 아래 의미가 같다.
    => class1class2가 둘 다 있는 요소에 해당 디자인을 적용하겠다.(class 교집합 개념)
/*[6] 색깔 변경 class*/
.circle.red {  
  background-color: #c0392b;
  box-shadow: 0 0 20px 5px #c0392b;
}
.circle.yellow {
  background-color: #f1c40f;
  box-shadow: 0 0 20px 5px #f1c40f;
}
.circle.green {
  background-color: #2ecc71;
  box-shadow: 0 0 20px 5px #2ecc71;
}


3) js

  • [7] querySelectorAll를 사용해 해당하는 요소들을 모두 가져온다.(배열 형태)
  • [8] 색을 변경할 신호등의 index이다.
  • [9] setInterval(function, 밀리초)를 사용하여 1초마다 함수를 실행한다.
    const circles = document.querySelectorAll('.circle');  //[7]
    let activeLight = 0;                        //[8]
    setInterval(changeLight, 1000);        //[9]

  • [10] class="circle red"circle로 초기화한다.

  • [11] 현재 색을 변경하고자 하는 요소이다.

  • [12] getAttribute('color')를 사용해 해당 요소의 사용자정의속성값(color)을 가져온다.

  • [13] 변경하고자 하는 요소에 classList.add를 사용해 클래스를 추가한다.
    (circle => circle orange)

    function changeLight() {
    circles[activeLight].className = 'circle';   // [10] remove init color
    activeLight++;                             
    
    if(activeLight > 2) {
      activeLight = 0;
    }
    
    const currentLight = circles[activeLight];   //[11]
    currentLight.classList.add(currentLight.getAttribute('color')); //[12], [13]
    }
반응형

댓글