html_css

스벅 예제: css 포지션, 애니메이션, JS 스크롤 이벤트

자무카 2022. 11. 6.

코딩 알려주는 누나.

스벅 예제: css 포지션, 애니메이션, JS 스크롤 이벤트

  1. css 포지션, z-index
  2. css 애니메이션
  3. js 스크롤 이벤트

html

<!-- https://www.youtube.com/watch?v=ru5FGYuycwY -->
<!-- 스타벅스 배경화면주소
https://www.starbucks.co.kr/common/img/main/fav_prod_bg_new.jpg
스타벅스 사진이미지 주소
https://image.istarbucks.co.kr/upload/common/img/main/2022/2022_NewYear_pick_img.png -->
<!--
이미지 가져오기 : 엘리먼트elements->하단 element.style{background: url(이미지 주소)}
position: relative, fixed
keframe
js : 선택.style.color:.....?...
-->

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="style.css">
</head>
<body>
    <section>
        <h1>PICK YOUR FAVORITE</h1>

    </section>
    <!-- <img src="images/fav_prod_bg_new.jpg" alt=""> css로 -->
    <img class="photo" src="images/2022_NewYear_pick_img.png" alt="">
    
<script src="main.js"></script>
</body>
</html>

css

body {
    margin: 0;
    height: 2000px;
    /* position: fixed; */
}

section {
    height: 800px; /* 아무것도 없으면, 백그라운드 이미지 표시 안됨 */
    background: url("images/fav_prod_bg_new.jpg") fixed;
}

.photo {
    position: absolute;
    top: 100px;
    right: 100px;
}
/* h1 width 속성! */
h1 {
    font-size: 6em;
    width:258px;
    color:white;
    font-family: sans-serif;
    position: absolute;
    top: 80px;
    left: 100px;
    animation: slide 1s ease-out;

}

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

main.js

1. querySelector로 h1 선택해서 변수 생성

2. 스크롤 이벤트 리스너를 만든다.

3. scroll 시, 스크롤 좌표를 변수에 저장해서, 200보다 커질 시, h1의 style.animation 값을 바꾼다.

// 스크롤 하면, 글자 뒤로. ( h1의 style.animation 속성 값을 바꾸기)
// 1. h1 선택해서 변수 생성
// 2. 스크롤 이벤트 리스너를 만든다.
// 3. scroll 시, 스크롤 좌표를 변수에 저장해서, 200보다 커질 시, h1의 style.animation 값을 바꾼다.
const mainText = document.querySelector("h1");
console.log(mainText);
window.addEventListener("scroll", function (){
    let value = window.scrollY;
    if (value > 200) {
        mainText.style.animation = "disappear 1s ease-out forwards"; //forwards
    } else {
        mainText.style.animation = "slide 1s ease-out";
    }
});

댓글