最も簡単な方法は、上下にスライドさせようとしているすべての要素に追加の一般的なクラス名を付けてから、アンカーのhref
属性を使用して実際のアンカーを要素に接続することです。以下の JavaScript の一部 (HTML に変更を加えたもの) は、現在の JavaScript と同じ機能を実行するだけでなく、スライダーを簡単に追加できます。
# the html
<a class='about slide-control' href='#about'>toggle the about section</a>
<a class='info slide-control' href='#info'>toggle the info section</a>
<a class='contact slide-control' href='#contact'>toggle the contact section</a>
<div class='slider' id='about'>
this is the about section
</div>
<div class='slider' id='info'>
this is the info section
</div>
<div class='slider' id='contact'>
this is the contact section
</div>
# the javascript
$('a.slide-control').click(function() {
$('div.slider').slideUp();
var target = $(this).attr('href');
$(target).slideDown('slow');
});
適切な HTML を追加するだけで、新しいスライダーを追加できます。
<a class='slide-control' href='#new_section'>Tell me more about this new section!</a>
<div class='slider' id='new_section'>
This is a great paragraph about the new section on our website!
</div>
または、既存のクラスを使用.slideUp
して、他の要素のメソッド呼び出しを次の前に追加することもできます.slideDown
。
$('a.about').click(function() {
$("#info").slideUp('slow');
$("#contact").slideUp('slow');
$("#about").slideDown('slow');
});
// repeat for each click handler