Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8576

JavaScriptとCSSアニメーションでタイピング風表示を行う

$
0
0

こんなやつ

Image from Gyazo

結論

iTyped.jsを使う。

一文字ずつ表示させる処理

HTML
<pid="typing"></p>
JavaScript
consttyping=(element,sentence)=>{[...sentence].forEach((character,index)=>{setTimeout(()=>{document.querySelector(element).textContent+=character;},200*++index);});}typing('#typing','Lorem ipsum dolor sit amet, consectetur adipisicing elit.');

特徴としては、第一引数のelementで取った要素内の文字列をスプレッド演算子を用いて配列化しています。
例えば、今回は長いので代わりにconsole.log([...'Hello'])を実行して確認してみると配列内は以下のようになっています。
Image from Gyazo

これをforEach200 * (index + 1)ms後に実行されるタイマーに一文字ずつ追加しています。

また、HTML内のテキストをタイピング表示にしたい場合は、一度textContentを取得した後で空にして、上記と同じ処理を行うと良いと思います。

カーソルのアニメーション

css
p::after{width:1px;content:'';border-right:1pxsolid;animation:flashing0.4slinearinfinite;}@keyframesflashing{0%{opacity:0;}}

こちらはとても単純で、疑似要素::afterでカーソルのようなものを描画し、それのopacityを切り替えて点滅を表現しています。

Image from Gyazo

動作デモ → https://jsfiddle.net/1wpbcrv2/


Viewing all articles
Browse latest Browse all 8576

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>