问题
I just can't figure out, why this slidetoggle does't work. It just runs once:
HTML:
<div class="text">bla bla bla bla
<br />
bla bla bla bla
<br />
bla bla bla bla
<br />
bla bla bla bla
<br />
bla bla bla bla
<br />
bla bla bla bla
<br />
bla bla bla bla
<br />
bla bla bla bla
<br />
bla bla bla bla
</div>
<div class="button">Show</div>
CSS:
.text{
height:0;
overflow:hidden;
}
.heightAuto{
height:auto;
}
FUNCTION:
$(function(){
$(".button").toggle(function()
{
var $text = $(".text");
var contentHeight = $text.addClass('heightAuto').height();
$text.removeClass('heightAuto').animate({ height: contentHeight}, 500);
}, function() {
$(".text").animate({ height: "0"}, 500);
});
}) ;
Here's the fiddle:
http://jsfiddle.net/QwmJP/10/
回答1:
beacause the contentHeight variable is 0 again, after the first animation.
if you don't overwrite it it'll work:
$(function() {
var $text = $(".text");
var contentHeight = $text.addClass('heightAuto').height();
$text.removeClass('heightAuto');
$(".button").toggle(function() {
$text.removeClass('heightAuto').animate({
height: contentHeight
}, 500);
}, function() {
$(".text").animate({
height: "0"
}, 500);
});
});
http://jsfiddle.net/QwmJP/13/
回答2:
Instead, use the following jQuery
$('.button').on('click', function() {
$('.text').slideToggle();
});
See this live example
来源:https://stackoverflow.com/questions/11252719/why-does-this-slide-toggle-only-run-once