JavaScriptでタイピングエフェクト
5413 ワード
実装の流れ
・HTMLで要素の設置。
・JavaScriptで文字列を一文字ずつタイピング風に出力する。
・CSSアニメーションと擬似要素でカーソルをつける。
HTMl
index.html<h2 id="js-typewriter" class="hero__title"></h2>
JavaScript
・文字列を出力する要素を指定する
・タイピング風に表示する文字列を指定する
・文字列を出力する要素を取得する
・文字列を一文字ずつ分割して配列に格納する
・配列内の文字を一定の秒間隔で一文字ずつ指定要素に出力する
split()
で文字列を一文字ずつ分割して、分割した文字列をsetTimeout()
で時間をずらして要素に入れる。type.jsconst typewriter = (param) => { let el = document.querySelector(param.el); let speed = param.speed; let string = param.string.split(""); window.setTimeout(function () { string.forEach((char, index) => { setTimeout(() => { el.textContent += char; }, speed * index); }); }, 500); }; typewriter({ el: "#js-typewriter", //要素 string: "タイピング風に文字が出力されます。", //文字 speed: 80 //速度 });
CSSアニメーション
animation-delay:;
を使って文字を出力し切った後からアニメーションを発生させるとよりリアリティ増します。
style.scss.hero__title { &::after { content: "|"; animation-name: typing; animation-duration: 1s; animation-iteration-count: infinite; animation-delay: 4s; } } @keyframes typing { from { opacity: 0; } to { opacity: 1; } }
Author And Source
この問題について(JavaScriptでタイピングエフェクト), 我々は、より多くの情報をここで見つけました https://qiita.com/Coco__syu/items/4b3b638ed21797cac3cc著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .