Computer >> 컴퓨터 >  >> 프로그래밍 >> HTML

HTML DOM Style 애니메이션(animation) 속성 완벽 가이드

CSS를 활용하면 요소 속성의 전환 과정을 애니메이션으로 표현할 수 있습니다. 애니메이션 효과는 animation 속성을 통해 정의하며, animation-name, animation-duration, animation-iteration-count 등 개별 하위 속성들을 하나로 묶어 축약형(shorthand) 형태로 사용할 수 있습니다.

문법(Syntax)

animation 속성의 기본 문법은 다음과 같습니다.

object.style.animation = "name duration timingFunction delay iterationCount direction fillMode playState"

속성 값(Values)

animation 속성에 사용할 수 있는 주요 값들은 아래와 같습니다.

설명
animation-name선택자(selector)에 바인딩할 키프레임(keyframe) 이름을 지정합니다.
animation-duration애니메이션이 한 사이클을 완료하는 데 걸리는 시간을 초(seconds) 또는 밀리초(milliseconds) 단위로 지정합니다.
animation-timing-function애니메이션의 진행 속도 곡선(가속/감속 패턴)을 지정합니다.
animation-delay애니메이션이 시작되기 전에 대기할 지연 시간을 지정합니다.
animation-iteration-count애니메이션이 반복 재생될 횟수를 지정합니다.
animation-direction애니메이션이 교대(alternate) 또는 역방향(reverse) 사이클로 재생될지 여부를 지정합니다.
animation-fill-mode애니메이션이 실행 중이지 않은 시간 동안 적용될 스타일 값을 지정합니다.
animation-play-state애니메이션이 현재 일시정지(paused) 상태인지 재생(running) 상태인지 지정합니다.
initial해당 속성을 기본(initial) 값으로 설정합니다.
inherit부모 요소의 속성 값을 상속받습니다.

예제(Example)

다음 예제는 JavaScript를 통해 버튼 클릭 시 div 요소에 적용된 애니메이션을 다른 애니메이션으로 동적으로 변경하는 코드입니다.

<!DOCTYPE html>
<html>
<head>
<style>
   div {
      width: 5px;
      height: 15px;
      background-color: limegreen;
      animation: demo 4s infinite;
   }
   @keyframes demo {
      from {width: 5px; background-color: limegreen;}
      to {width: 400px; background-color: darkgreen;}
   }
   @keyframes demo1 {
      from {height: 5px; background-color: limegreen;}
      to {height: 400px; background-color: darkgreen;}
   }
</style>
<script>
   function changeAnimation() {
      document.getElementById("DIV1").style.animation = "demo1 4s 2";
   }
</script>
</head>
<body>
<button onclick="changeAnimation()">CHANGE ANIMATION</button>
<p>위 버튼을 클릭하면 아래 애니메이션이 변경됩니다.</p>
<div id="DIV1"></div>
</body>
</html>

실행 결과(Output)

위 코드를 실행하면 초록색 막대가 가로 방향으로 넓어지는 애니메이션이 무한히 반복됩니다.

HTML DOM Style 애니메이션(animation) 속성 완벽 가이드

CHANGE ANIMATION 버튼을 클릭하면, 애니메이션이 세로 방향으로 높아지는 새로운 애니메이션(demo1)으로 전환되며 총 2회 재생됩니다.

HTML DOM Style 애니메이션(animation) 속성 완벽 가이드