LoginSignup
6
6

More than 3 years have passed since last update.

JavaScriptでロード画面を作る

Posted at

JavaScript勉強中、「文字にアニメーションをつける」解説動画を見つけたので、ロード画面として作ってみました。

Demoページ

コード

html

<body>
    <!-- ロード画面 -->
    <div class="init">
        <h1 class="loading">Now Loading...</h1>
    </div>
    <!-- ロード後の画面 -->
    <div class="main">
    <h1>メイン画面</h1>
  </div>
</body>

css

*{
    padding: 0;
    margin: 0;
}

.init{
    background: black;
    width: 100%;
    height: 100vh;
    position: fixed;
}

.init h1{
    color: #ecf0f1;
    text-align: center;
    line-height: 100vh;
    font-size: 3em;
}

span{
    transition: all .3s;
}

.coloring{
    color: #812990;
}

.fadeout {
    animation : fadeOut 2s;
  }
  @keyframes fadeOut {
    0% {
      opacity: 1;
    }
    100% {
      opacity: 0;
    }
  }

javascript

// ロード中、表示する文字一つ一つに<span>をつける
const text = document.querySelector('.loading');
const strText = text.textContent;
const splitText = strText.split("");
text.textContent = '';

for(let i=0; i < splitText.length; i++){
    text.innerHTML += "<span>" + splitText[i] + "</span>";
}

// 160ミリ秒ごとspanにcoloringクラスを加える
let char = 0;
let timer = setInterval(setFade, 160);

function setFade(){
    const span = text.querySelectorAll('span')[char];
    span.classList.add('coloring');
    char++;
    // 最後の文字に到達したら二つの関数を呼び出す
    if(char === splitText.length){
        finish();
        fadeOut();
    }
}

function finish(){
    clearInterval(timer);
    timer = null;
}

// ロード画面を作るdivにfadeoutクラスを加える
function fadeOut(){
    const init = document.querySelector('.init');
    init.classList.add('fadeout');
    // 2秒後にdisplay: none;を加える
    setTimeout(function(){
        init.style.display = 'none';
    }, 2000);
}
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6