.slideToggle auto scroll down to reveal content
I am using .slideToggle to open a panel when the user clicks a link:
<script type="text/javascript">
$(document).ready(function(){
$(".btn-slide").click(function(){
$("#panel").slideToggle("slow");
$(this).toggleClass("active");
return false;
});
});
</script>
The content of the toggled div (#panel) is taller than the height of 开发者_Python百科the containing div so scorllbars show up. I would like the vertical scrollbar to automatically scroll down to the reveal the new content when the div gets toggled. I think I could probably do this with .scrollTop to make this happen but Im not sure how to go about making it happen at the same time... Any ideas?
EDIT: There seems to be a consensus that this is the best way to go about achieving what I described:
<script type="text/javascript">
$(document).ready(function(){
$(".btn-slide").click(function(){
var $panel = $("#panel");
$panel.slideToggle("slow");
if ($panel.is(':visible')){
$panel.parent().scrollTop($panel.height()-$panel.parent().height());
}
$(this).toggleClass("active");
return false;
});
});
</script>
This makes the panel slide but the scroll down effect isn't working..
I've done something like this before:
$(".btn-slide").click(function(event){
if ( $(this).hasClass("active"))
{
$(this).removeClass("active");
$("#panel").slideUp("slow");
}
else
{
$(this).addClass("active");
$("#panel").slideDown("slow");
var destination = $("#container ").offset().top + $("#container").height();
$("#container").animate({ scrollTop: destination},"slow");
//or
//$("#container").animate({ scrollTop: destination},"slow", "fx_name_here");
}
event.preventDefault();
});
Html:
<a href="#" class="btn-slide">Fire Panel</a>
<div id="container">
<div id="panel">sdfsdfsdfs</div>
</div>
Would that help you?
EDIT:
If you download the jQuery Easing Plugin you can add different effects to the sliding, adding the fx name into the code (commented out line in answer)
Improved code so there is less code but same effect.
精彩评论