最简单的方法是为您尝试向上/向下滑动的所有元素提供一个额外的通用类名,然后使用锚点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