[JS]ユーザビリティに配慮したアコーディオンを実装するチュートリアル
Post on:2010年5月20日
sponsorsr
ユーザビリティに配慮しつつ、jQueryのバグにも対応したシンプルなアコーディオンを実装するチュートリアルをSoh Tanakaから紹介します。

Simple Accordion w/ CSS and jQuery
デモページ
アコーディオンのロジックは下記の通りです。
- 最初にデフォルトの設定します。
 一番目のアコーディオンを開いて、アクティブな状態にします。
- クリックをすると。
 クリックされたアコーディオンのアイテムは開くのか閉じるのか判定します。
- 「hidden」(閉じた状態)のアイテムをクリックすると、
- 全てのアイテムから「active」を取り去り、閉じます。
- クリックされたアイテムは「active」になり、すぐにスライドダウンして開きます。
ロジックのイメージは、下記のようになります。

実装のイメージ
.
HTML
アコーディオンのアイテムはシンプルに実装されており、h2要素とdiv要素から成っています。
| 1 2 3 4 5 6 7 8 | <textarea name="code" class="html" cols="60" rows="5"> <h2 class="acc_trigger"><a href="#">Web Design & Development</a></h2> <div class="acc_container"> 	<div class="block"> 	<!--Content Goes Here--> 	</div> </div> </textarea> | 
CSS
CSSで注意を払うべき重要なポイントは二つです。
- 「.acc_container」で指定している、アイテムの幅は固定幅にしています(%やemではありません)。これはjQueryのバグにスライドする際にジャンプしたりスキップするのを防ぎます。
- ネストしているdiv要素の「.acc_container .block」にpaddingを指定しています。これは開いたり閉じたりするアニメーションでのバグを防ぎます。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | <textarea name="code" class="css" cols="60" rows="5"> h2.acc_trigger { 	padding: 0;	margin: 0 0 5px 0; 	background: url(h2_trigger_a.gif) no-repeat; 	height: 46px;	line-height: 46px; 	width: 500px; 	font-size: 2em; 	font-weight: normal; 	float: left; } h2.acc_trigger a { 	color: #fff; 	text-decoration: none; 	display: block; 	padding: 0 0 0 50px; } h2.acc_trigger a:hover { 	color: #ccc; } h2.active {background-position: left bottom;} .acc_container { 	margin: 0 0 5px; padding: 0; 	overflow: hidden; 	font-size: 1.2em; 	width: 500px; 	clear: both; 	background: #f0f0f0; 	border: 1px solid #d6d6d6; 	-webkit-border-bottom-right-radius: 5px; 	-webkit-border-bottom-left-radius: 5px; 	-moz-border-radius-bottomright: 5px; 	-moz-border-radius-bottomleft: 5px; 	border-bottom-right-radius: 5px; 	border-bottom-left-radius: 5px; } .acc_container .block { 	padding: 20px; } </textarea> | 
JavaScript
スクリプトのベースにはjQueryを使用し、下記のスクリプトを記述します。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <textarea name="code" class="js" cols="60" rows="5"> $(document).ready(function(){ //Set default open/close settings $('.acc_container').hide(); //Hide/close all containers $('.acc_trigger:first').addClass('active').next().show(); //Add "active" class to first trigger, then show/open the immediate next container //On Click $('.acc_trigger').click(function(){ 	if( $(this).next().is(':hidden') ) { //If immediate next container is closed... 		$('.acc_trigger').removeClass('active').next().slideUp(); //Remove all .acc_trigger classes and slide up the immediate next container 		$(this).toggleClass('active').next().slideDown(); //Add .acc_trigger class to clicked trigger and slide down the immediate next container 	} 	return false; //Prevent the browser jump to the link anchor }); }); </textarea> | 
スクリプトがオフの時は、各エレメントが成り行きで配置されます。

スクリプトがオフの時のキャプチャ
sponsors















