jQueryトグル
jQueryの簡単なトグル
以下のようなhtml
<div> <h1>ここに見出しが入ります。</h1> <div class="contents"> <p>ここにテキストが入ります。</p> <p>ここにテキストが入ります。</p> <p>ここにテキストが入ります。</p> </div> </div><div> <h1>ここに見出しが入ります。</h1> <div class=“contents”> <p>ここにテキストが入ります。</p> <p>ここにテキストが入ります。</p> <p>ここにテキストが入ります。</p> </div> </div>
<div> <h1>ここに見出しが入ります。</h1> <div class=“contents”> <p>ここにテキストが入ります。</p> <p>ここにテキストが入ります。</p> <p>ここにテキストが入ります。</p> </div> </div>
.contentsを非表示にしておく。
.contents {
display: none;
}
h1をクリックしたら同グループの.contentsを表示する。
開く/閉じるの判定はh1にactiveクラスがついているかどうか
$('h1').click(function () {
if ( $(this).hasClass('active') ) {
$(this).parent().find('.contents').css({'display':'none'});
$(this).removeClass('active');
} else {
$(this).parent().find('.contents').css({'display':'block'});
$(this).addClass('active');
}
});
display:block/noneではなく.slideUp()、.slideDown()などでも
またh1にactiveクラスがつくので矢印画像の変更をその都度など