jQuery(タイピング風テキストアニメーション)

jQuery

jQueryを使ってタイピング風テキストアニメーションを実装しよう。

作成

1.以下のファイルをダウンロードし、好きな場所に解凍する。


2.先ほどダウロードしたフォルダはjQueryを用いたWebサイト開発に最適な構成である。これを複製していくことによって新しいプロジェクトを作成する。Templateフォルダを複製しフォルダ名をtextanimとしよう。

3.index.htmlを以下のように編集

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>タイトル</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
    </head>
    <body>
      <div id="animateContainer">
        <p class="animate_text">public class Main{</p>
        <p class="animate_text idt1">public static void main(String[] args){</p>
        <p class="animate_text idt2">System.out.println("hello world");</p>
        <p class="animate_text idt1">}</p>
        <p class="animate_text">}</p>
      </div>
      <script src="js/vendor/jquery-1.12.4.min.js"></script>
      <script src="js/vendor/jquery-ui-1.12.1.min.js"></script>
      <script src="js/vendor/jquery.easing.1.3.js"></script>
      <script src="js/main.js"></script>
    </body>
</html>

アニメーションさせたい要素をanimaterContainerで囲み実際にアニメーションさせたい要素にanimate_textクラスを付与する。こうすることで1行1行順番にアニメーションさせることができる。idt1,idt2がついた要素は左にインデントされる。

4.main.cssを以下のように編集

#animateContainer{
  margin:20px auto;
  background:green;
  padding:10px 40px 20px;
  width:500px;
  height:220px;
  color:white;
  border:5px solid brown;
  font-size:20px;
}
.idt1{
  margin-left:40px;
}
.idt2{
  margin-left:80px;
}

animateContainerは今回は黒板風にしてみたが、すきなようにアレンジしてもらいたい。

5.main.jsを以下のように編集

$(function () {
	function textAnimator($container) {
		$animate_texts=$container.find('.animate_text');
		const STEP = 80; //文字送りのスピード
		const CURSOR = '<span class="cur">_</span>'; //カーソル
		let index = 0; //何番目の要素か
		let orgs = []; //もともとの文字列を保存しておく配列
		$animate_texts.each(function () {
			orgs.push($(this).text()); //もともとの文字列を配列にプッシュ
			$(this).text(''); //文字列を空にする
		});
		function moveText($target) {
			let num = 0;
			$target.append(CURSOR); //カーソルを末尾に追加
			const $cur = $target.find('.cur'); //追加したspanタグをキャッシュ
			for (let i = 0; i < orgs[index].length; i++) {
				setTimeout(function () {
					$cur.remove();//spanタグを削除
					$target.append(orgs[index].charAt(num));//もともとの文字列から一文字を取り出して$target(pタグ)に追加
					if (i != orgs[index].length - 1) {
						$target.append($cur);//最後の文字でなければカーソルを追加
					}
					num++;
				}, i * STEP);
			}
			//次の$target(pタグ)があれば
			if (index < $animate_texts.length - 1) {
				setTimeout(function () {
					index++; //indexをひとつ進めて
					moveText($animate_texts.eq(index)); //起動
				}, orgs[index].length * STEP); //文字数*STEP時間待ったあったとに

			}
		}
		//最初のtarget(pタグ)に対してmoveTextを起動
		moveText($animate_texts.eq(index));
	}
	//textAnimatorを実行
	textAnimator($('#animateContainer'));
});

一旦、オリジナルな文章を配列に保存後、pタグのテキストを空にしている。
あとは一文字ずつ取り出しながら末尾にカーソルを付与していっている。
その行の描画終わると次のpタグに遷移していく。
すべてのpタグの描画が終われば終了だ。

コメント

タイトルとURLをコピーしました