jQueryのanimate()メソッドを使ってHTML要素にアニメーション効果をつける方法について解説します。jQuery初心者向けに簡単なサンプルコードと共に説明します。
目次
1. animate()メソッドの基本的な使い方
jQueryの「animate()メソッド」の基本書式は以下の通りです。
●animate()メソッドの基本書式
$("セレクター").animate("CSSプロパティ")
HTML要素に動きをつける「animate()メソッド」の使い方について、実際のサンプルコードで動作を確認してみましょう。「jQuery_Sample1.html」をコピーして任意の場所に保存して下さい。
 
●jQuery_Sample1.html --------------------
<!DOCTYPE html>
<html lang="ja">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script> 
$(document).ready(function(){
 $("button").click(function(){
  $("div").animate({opacity: "0.5"});
 });
});
</script> 
<style>
div {
	margin:10px;
	padding:10px;
	background:#aaa;
	height:100px;
	width:100px;
}
</style>
</head>
<body>
<button>クリックして下さい</button>
<div>ボックス</div>
</body>
</html>
--------------------
 
サンプルコードでは、高さ・幅が100pxのボックスを作成しています。「animate()メソッド」を使ってこのボックス要素の透明度を指定してみましょう。「animate()メソッド」の引数に「{opacity: "0.5"}」を渡すと、ボタンをクリックした時に背景色が薄くなります。
▲ページトップへ戻る
2. animate()メソッドをボックスを左に移動させる方法
「animate()メソッド」を使って、ボックスを左に動かす事ができます。サンプルコードの「jQuery_Sample2.html」をコピーして、任意の場所に保存して下さい。
 
●jQuery_Sample2.html --------------------
<!DOCTYPE html>
<html lang="ja">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script> 
$(document).ready(function(){
 $("button").click(function(){
  $("div").animate({ marginLeft: "200px" });
 });
});
</script> 
<style>
div {
	margin:10px;
	padding:10px;
	background:#aaa;
	height:100px;
	width:100px;
}
</style>
</head>
<body>
<button>クリックして下さい</button>
<div>ボックス</div>
</body>
</html>
--------------------
 
「animateメソッド」の引数に「marginLeftプロパティ」を指定します。値には200pxを指定していますので、ボタンをクリックするとボックスが左に移動していきます。
▲ページトップへ戻る
3. animate()メソッドを使ってボックスをゆっくりと大きくする方法
「animate()メソッド」の第二引数にアニメーションの動作時間を指定してみましょう。サンプルコードの「jQuery_Sample3.html」をコピーして、任意の場所に保存して下さい。
 
●jQuery_Sample2.html --------------------
<!DOCTYPE html>
<html lang="ja">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script> 
$(document).ready(function(){
 $("button").click(function(){
  $("div").animate({ 
  marginLeft: "100px", 
  width: "200px",
  opacity: 0.5,
  }, 5000);
 });
});
</script> 
<style>
div {
	margin:10px;
	padding:10px;
	background:#aaa;
	height:100px;
	width:100px;
}
</style>
</head>
<body>
<button>クリックして下さい</button>
<div>ボックス</div>
</body>
</html>
--------------------
 
「animate()メソッド」の第一引数には、ボックスを左に移動させるmarginLeftプロパティの他、ボックスの横幅(width)を「200px」、透明度(opacity)を「0.5」に指定しています。第二引数には「5000」を指定しましたので、ボタンをクリックするとボックスが5秒かけて、左側に移動すると同時に横幅が大きくなり、背景色が薄くなっていきます。
▲ページトップへ戻る
関連記事:jQueryのダウンロードから使い方まで
関連記事:jQuery入門~導入から基本の使い方まで~
関連記事:現場で使えるjQueryプラグイン22選
関連記事:jQuery入門オススメ本 7選
関連記事:jQueryのhideメソッドで要素を非表示にする方法
関連リンク:jQuery API Document(animate)