자바스크립트 setInterval 로 글자 출력하기

버건디·2022년 12월 1일
0
post-thumbnail

🔍 완성 화면

🔍 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>Hello Game World</title>
    <script src="https://kit.fontawesome.com/412379eca8.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="style.css">
    <script src="main.js" defer></script>
</head>

<body>
    <div class="container">
        <div class="title-container">
            <div class="h1-conatiner">
                <h1 id="intro-title" class="intro-title">
               
                </h1>

            </div>

            <div class="intro-show"><button id="introShowBtn" class="intro-show-btn">
                    <i class="fa-solid fa-angles-down"></i>
                </button></div>
        </div>
    </div>

</body>

</html>

🔍 CSS

*{
    box-sizing: border-box;
}

body{
    margin: 0;
    height: 100vh;
    width: 100vw;
    display: flex;
    justify-content: center;
    align-content: center;
    color: #fff;
    background-color: rgb(124, 40, 40);
}

.container{
    display: flex;
    justify-content: center;
    align-content: center;
    width: 100vw;

}

.title-container{
    display: flex;
    justify-content: center;
    align-content: center;
    flex-direction: column;
}

.intro-title{
    font-size: 70px;
    text-align: center;
}

.intro-title::after{
    content: '|';
    animation: show 0.5s ease-in-out infinite;
}

.intro-show{
    display: flex;
    justify-content: center;
    align-items: center;
}

.intro-show-btn{
    padding: 20px;
    font-size: 70px;
    background-color: rgb(124, 40, 40);
    color: #fff;
    border: none;
    cursor: pointer;
    position: absolute;
    bottom: 30;
    opacity: 0;
}

.intro-show-btn.show{
    animation: show 0.5s ease-in;
    animation-fill-mode: forwards;
}


@keyframes show{
    from{
        opacity: 0;
    }
    to{
        opacity: 1;
    }
}

🔍 자바스크립트

const introTitle = document.getElementById("intro-title");
const introShowBtn = document.getElementById("introShowBtn");
const TitleText = "안녕하세요! BRGNDY 입니다!";

const showTitleText = () => {
  const copyTitleText = [...TitleText];
  let index = 0;
  const showText = setInterval(() => {
    introTitle.innerHTML += copyTitleText[index++];
    if (copyTitleText[index] === " ") {
      introTitle.innerHTML += "<br>";
    } else if (index === copyTitleText.length) {
      clearInterval(showText);
      introShowBtn.classList.toggle("show");
    }
  }, 200);
};

window.onload = () => {
  showTitleText();
};

🔍 알아가기

원래는 copyTitleText를 forEach 문을 통해서 setInterval를 통해 출력을 하려 했는데,

한번에 모든 글자가 출력이 되는 오류가 발생했다.

아예 index 값을 하나씩 높여줌으로써 문제를 해결하였다!

profile
https://brgndy.me/ 로 옮기는 중입니다 :)

0개의 댓글