0

この質問は、私が実際に答えを得た以前の質問に基づいていますが、slidetoggle要素が1つだけです:link

私はanimateメソッドを使用して、「非表示」要素をバックグラウンドでロードします。それ以外の場合は、slidetoggleを使用できますが、これによりdisplay:noneが表示されます。

これが私がこれまでに得た関数ですが、h2ごとに1回だけ実行されます。

HTML:

<h2>Show</h2>
    <div class="content">
        text text text
        <br />
        text text text
        <br />
        text text text
    </div>

<h2>Show</h2>
    <div class="content">
        text text text
        <br />
        text text text
        <br />
        text text text
    </div>

CSS:

.content {
  height: 0;
  overflow: hidden;
}

.heightAuto {
    height: auto;
}​

脚本:

$(function(){  

    $("h2").toggle(function()

     {    
       var $content = $(this).next(".content");
       var contentHeight = $content.addClass('heightAuto').height();
       $content.removeClass('heightAuto');

       $content.removeClass('heightAuto').animate({ height: contentHeight}, 500);

     }, function() {

        $(this).next(".content").animate({ height: "0"}, 500);    

     });
});​

高さを再び自動に設定するのは問題ですか?トリックが見つかりません。

ここにもフィドルがあります:jsfiddle

4

3 に答える 3

1

サイズ変更されないラッパーを追加します。

<div class="content"><div class="inner">
    text text text
    <br />
    text text text
    <br />
    text text text
</div></div>

次に、このJSを使用します。

jQuery(function($) {  
    $('h2').toggle(function() {
        var $content = $(this).next('.content');
        $content.animate({ height: $content.find('> .inner').height() }, 500);
    }, function() {
        $(this).next('.content').animate({ height: 0 }, 500);       
    });
});

編集: HTMLで余分なラッパーを使用したくない場合は、JSにラッパーを追加させることができます。

jQuery(function($) {  
    $('h2').toggle(function() {
        var $content = $(this).next('.outer');
        $content.animate({ height: $content.find('> .content').height() }, 500);
    }, function() {
        $(this).next('.outer').animate({ height: 0 }, 500);       
    }).next('.content').wrap('<div class="outer" style="height:0;overflow:hidden"></div>');
});​

このアプローチを使用する場合は、.contentブロックのCSSを削除する必要があります。更新されたフィドルを参照してください:http://jsfiddle.net/QwmJP/21/

于 2012-06-29T19:25:12.087 に答える
1

overflow:hidden問題を解決するには、高さが。の場合に設定します0

ライブデモを参照

JS:

$(function(){
    $("h2").toggle(
        function() {    
            var $content = $(this).next(".content");
            var contentHeight = $content.addClass('heightAuto').height();
            if (contentHeight == 0) {
                contentHeight = $content.attr({
                    style:'overflow:hidden'
                }).height(); 
            }            
            $content.removeClass('heightAuto').animate({ height: contentHeight}, 500);
        }, 
        function() {
            $(this).next(".content").animate({height:0}, 500);
        });
});​
于 2012-06-29T20:19:06.973 に答える
0

初めて高さを0に設定したため、次回はゼロになり、.height()値はゼロを返します。

代わりにoffsetHeightプロパティを使用してください。これは常にコンテンツの自然な高さになります。

于 2012-06-29T19:11:31.470 に答える