Why does this slide/toggle only run once?

坚强是说给别人听的谎言 提交于 2019-12-25 18:59:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!