テキストタイピング風アニメーションの実装方法

by interlife

HTML

<h1 class="text-wrap">
  <!-- PCでは1行で表示、スマホでは隠す -->
  <span class="text sp_hidden">テキストタイピング風アニメーションの実装方法</span>
  
  <!-- スマホでは2行で表示、PCでは隠す -->
  <span class="text pc_hidden">テキストタイピング風</span>
  <span class="text pc_hidden">アニメーションの実装方法</span>
</h1>

SCSS

// ============================================
// Typewriter Line(タイプライター帯テキスト)
// ============================================
// .tw-cursor は JS が最終行末尾に挿入

@keyframes tw-cursor-blink {
  0% { opacity: 0; }
  20% { opacity: 1; }
  70% { opacity: 1; }
  100% { opacity: 0; }
}

.text-wrap {
  min-height: 88px;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.text {
  padding: 0 8px 4px;
  display: none; // JSタイプライター開始時に inline-flex へ切り替え
  align-items: center;
  position: relative;
  height: 44px;
  line-height: 1;
  color: #fff;
  background: #000;

  & + & { margin-top: 6px; }

  &:empty { display: none; }

  .tw-cursor {
    position: absolute;
    top: 50%;
    right: 6px;
    transform: translateY(-50%);
    width: 2px;
    height: 82%;
    animation: tw-cursor-blink 1.6s ease-in-out 1 forwards;
    background: #fff;
  }
}

JavaScript

(function () {
  const LINE_SEL   = '.text';
  const CHAR_DELAY = 70;
  const LINE_GAP   = 200;

  function runTypewriter(container, initDelay) {
    const isSP = window.matchMedia('(max-width: 768px)').matches;
    const lineEls = Array.from(container.querySelectorAll(LINE_SEL)).filter(el => {
      if (el.classList.contains('sp_hidden') && isSP) return false;
      if (el.classList.contains('pc_hidden') && !isSP) return false;
      return true;
    });
    
    if (!lineEls.length) return;

    const texts = lineEls.map(el => el.textContent.trim());
    lineEls.forEach(el => { el.textContent = ''; });

    let delay = initDelay;

    texts.forEach((text, lineIdx) => {
      const lineEl = lineEls[lineIdx];
      const isLast = lineIdx === texts.length - 1;

      if (isLast) {
        const textNode = document.createTextNode('');
        const cursor   = document.createElement('span');
        cursor.className = 'tw-cursor';
        cursor.addEventListener('animationend', () => cursor.remove(), { once: true });

        for (let c = 1; c <= text.length; c++) {
          const d = delay + (c - 1) * CHAR_DELAY;
          setTimeout(() => {
            if (c === 1) {
              lineEl.style.display = 'inline-flex';
              lineEl.appendChild(textNode);
              lineEl.appendChild(cursor);
            }
            textNode.textContent = text.slice(0, c);
          }, d);
        }
      } else {
        for (let c = 1; c <= text.length; c++) {
          const d = delay + (c - 1) * CHAR_DELAY;
          setTimeout(() => {
            if (c === 1) lineEl.style.display = 'inline-flex';
            lineEl.textContent = text.slice(0, c);
          }, d);
        }
      }

      delay += text.length * CHAR_DELAY + LINE_GAP;
    });
  }

  // スクロールで表示されたタイミングで起動
  const targetWraps = document.querySelectorAll('.text-wrap');
  if (targetWraps.length && 'IntersectionObserver' in window) {
    const...