▲TOPへ戻る

【CSS】transition-delayを使って、テキストを1文字ずつアニメーションさせる方法

Scroll to Begin

前回のページを見ていない方は、まずこのページをみてください。

1文字ずつアニメーション

今回は、animationではなく、transition-delayを使ってアニメーションさせます。

javascript
   //文字を表示させるところ
  const animationTarget = document.querySelector(".Text"); 
  const texts = animationTarget.textContent;
  textsArray = [];
  animationTarget.textContent = "";
  //HTMLの生成
  for (let j = 0; j < texts.split("").length; j++) {
    const textT = texts.split("")[j];
    if (textT === " ") {
      textsArray.push(" ");
    } else {
      textsArray.push(
        '<span class="ani" style="transition-delay: ' +  //  ここがポイント
          (j * 0.1 + 0.5) +
          's;">' +
          textT +
          "</span>"
      );
    }
  }
  //文字の書き出し
  for (let k = 0; k < textsArray.length; k++) {
    animationTarget.innerHTML += textsArray[k];
  }
  //一文字ずつクラスを付与
  const ani = document.querySelectorAll(".ani");
    setTimeout(animation, 100);
    function animation(){
      ani.forEach(element => {
        element.classList.add("ani1");
      });
  } 
CSS
  .Text {
    position: relative;
    height: 100px;
    display: flex;
    justify-content: center;
  }

  .Text .ani {
    font-size: 2em;
    color: blue;
    text-shadow: 3px 3px 5px #fff;
    font-weight: bold;
    transform: translateX(-200px);
    transition: all 0.5s ease;
    opacity: 0;
  }
  .Text .ani.ani1 {
    transform: translate(0px);
    opacity: 1;
  }
point

transitionとtransformで、クラスが付与されたらアニメーションさせる。

setTimeoutで画面が読み込まれてから100ms後にクラスを追加

こんな記事も読まれています。

profile

パソコン好きなガオ

コロナ禍によるステイホームを機にプログラミングを学ぶ。パソコンに関してはプロではないが、ちょっと詳しい程度。

パソコン

javascript

カメラ

ブログ