[CSS] @keyframes 사용하기
본문 바로가기
프레임워크/CSS

[CSS] @keyframes 사용하기

by 은돌1113 2022. 1. 18.

CSS에 @keyframes와 animation을 사용해 보았다!

 

  [ 실행 화면 ]  

  [ 전체 코드 ]  

더보기
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- CSS -->
    <link rel="stylesheet" href="animation.css" />
  </head>
  <body>
    <!-- HTML -->
    <section>
      <h1>PICK YOUR FAVORIT</h1>
      <img
        class="photo"
        src="https://image.istarbucks.co.kr/upload/common/img/main/2022/2022_NewYear_pick_img.png"
      />
    </section>
    <!-- JS -->
    <script src="animation.js"></script>
  </body>
</html>

 

body {
  margin: 0;
  height: 2000px;
}

section {
  height: 800px;
  background: url(https://www.starbucks.co.kr/common/img/main/fav_prod_bg_new.jpg)
    fixed; /* 간지 */
}

.photo {
  position: absolute; /* 화면에 절대적인 속성 (부모에 절대적 X) */
  top: 100px;
  right: 200px;
}

h1 {
  font-size: 6em;
  width: 258px;
  color: white;
  font-family: sans-serif;

  position: absolute;
  top: 80px;
  left: 400px;

  animation: slide 2s ease-out;
}

@keyframes slide {
  from {
    left: -100px;
    opacity: 0;
  }

  to {
    left: 400px;
    opacity: 1;
  }
}

@keyframes disappear {
  from {
    left: 400px;
    opacity: 1;
  }

  to {
    left: -100px;
    opacity: 0;
  }
}

 

let mainText = document.querySelector("h1");

window.addEventListener("scroll", () => {
  let value = window.scrollY;

  if (value > 300) {
    mainText.style.animation = "disappear 2s ease-out forwards";
    // ease-out : 스무스 하게 이동
    // forwards : 애니메이션 유지
  }else{
    mainText.style.animation = "slide 2s ease-out";
  }
});

댓글