jQuery box height problem - using slideUp/Down

2019-08-18 08:37发布

问题:

I have a box on my site that when a button is clicked, the box slides up, some new text is loaded into it, and then it slides down revealing the new text. Here is the code I have written for it in jQuery:

$("#generate").click(function(){
    var $target = $("#lyric");
    $target.slideUp();
    $target.queue(function(){
        $("#generate").text('Loading...');
        $target.load('lyrics.php', function(){
            $("#generate").text('Get another lyric');
            $target.dequeue();
        });
    });
    $target.slideDown();
});

The problem is that the box changes height once it has slid up, because the new text may be shorter or longer. This means that when the box slides down it jerks once it gets to the 'old' height of the box to the new height of the box.

Here is an example of the html, everything inside 'lyric' is spat out by the 'lyric.php' file:

<div id="lyric">
<div>
<p class="quote">Come ride with me, through the veins of history, I'll show you how god, falls asleep on the job</p>
<p><span class="artist"> - Muse, </span><span class="song">Knights Of Cydonia</span></p>
</div>
</div>

And the CSS:

#lyric div {
    padding: 18px 0;
}
p.quote {
    border-left: 2px solid rgb(100, 130, 130);
    font-style: italic;
    padding-left: 16px;
    padding-top: 0;
}
.artist {
    color: #E8E8E8;
    font-weight: bold;
}

I tried mucking around with a custom animation, but I haven't been able to mimic slideUp/Down and sort the box height issue out. Any help is greatly appreciated.

回答1:

I haven't tested this, but off hand I'd say I think you should put your slideDown() inside your load success function:

$("#generate").click(function(){
    var $target = $("#lyric");
    $target.slideUp();
    $target.queue(function(){
        $("#generate").text('Loading...');
        $target.load('lyrics.php', function(){
            $("#generate").text('Get another lyric');
            $target.dequeue();
            $target.slideDown();
        });
    });
});
  • that way it waits until loading is complete, and the size is determined, before attempting to resize the box.