Javascript, CSS - 나타나기 효과

animation

Posted by Yan on February 2, 2021

나타나기 효과

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="src/styles.css" />
  </head>

  <body>
    <header>
      <img
        src="https://images.unsplash.com/photo-1580654842920-37b786f32bfc?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80"
        alt=""
      />
    </header>
    <div class="intro">
      <div class="intro-title">
        <h2>나타나기 효과</h2>
      </div>
      <div class="intro-content">
        <div class="intro-text">
          <h2>fade in효과와 살짝 위로 올라오는 효과를 넣어요</h2>
          <p>
            Lorem ipsum dolor sit amet consectetur adipisicing elit. Earum nisi
            culpa hic, odio, doloremque doloribus odit quia eius
          </p>
        </div>
        <img
          src="https://images.unsplash.com/photo-1588534141300-b49abbd25ff8?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=634&q=80"
        />
      </div>
    </div>
    <script src="src/index.js"></script>
  </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
header img {
  width: 100%;
}

.intro-content {
  display: flex;
}

.intro-content img {
  width: 60%;
  position: absolute;
  right: 0;
}

.intro-text {
  width: 30%;
  opacity: 0;
  transform: translateY(20px);
  transition: 0.5s all ease-in-out;
}

.intro-appear {
  opacity: 1;
  transform: translateY(0px);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function scrollAppear() {
  var introText = document.querySelector(".intro-text");
  var introPosition = introText.getBoundingClientRect().top;
  //introText의 위치와 뷰포트의 최상단 위치의 거리차를 알려준다.
  var screenPosition = window.innerHeight / 1.2;
  //뷰포트의 높이를 찾는다. 1.2로 나눈 이유는 뷰포트의 일정 높이로 스크롤 했을 때 나타나게 하기 위함이다.

  if (introPosition < screenPosition) {
    introText.classList.add("intro-appear");
  }
}

window.addEventListener("scroll", scrollAppear);
//스크롤 할 때 효과과 나타나도록 window scroll에 이벤트를 넣는다.

알게 된 것

  1. translateY

translateY(길이 또는 퍼센트)

element를 y축으로 움직이게 함

  1. Element.getBoundingClientRect()

DOMRect : 사각형을 의미함

.getBoundingClientRect()를 이해하려면 window와 viewport 개념을 알아야하는데,

모니터상 보이는 부분 까지를 viewport라 부르고,

모니터에 안보이는 스크롤 하면 볼 수 있는 콘텐츠 영역까지 포함한 것을 window라 한다.

window 상에서 가지는 위치(좌표)를 절대위치라 하고,

viewport 상에서 가지는 위치를 상대위치라 한다.

스크롤을 하면 상대위치는 바뀌기 때문에 음수값이 나올 수도 있다.

기준은 부모요소로 정해지는데,

부모요소가 position: relative면 상대위치를 offsetTop을 사용하여 나타낸다

relative가 아니라면 relative를 부모 요소를 탐색하고, 상위요소가 전부 relative가 아니라면 절대위치 값을 리턴하게 된다.