2011-05-11 78 views
0

我想對部分顯示一個列表,然後當一個按鈕被點擊我想通過使用全高度更改類的按鈕和顯示的完整列表的div,那麼當再次點擊按鈕時,我希望它從最初的揭示開始,而不是隱藏整個事情。通過動畫的高度(不隱藏所有內容)顯示內容

HTML:

<section id="newsletters"> 
<h4><a href="#rss"></a><span>Related</span> Button</h4> 
    <nav> 
     <ul> 
      <li>1</li> 
      <li>1</li> 
      <li>1</li> 
      <li>1</li> 
      <li>1</li>  
     </ul> 
    </nav> 
<a class="hide" href="#">Show/Hide 
</a></section> 

jQuery的

$('section#newsletters .hide').click(function() { 
    $('section#newsletters nav').toggle(400); 
    return false; 
    }); 

回答

3

您必須創建自己的切換器。簡單而直接:

var toggle = true, oldHeight = 0; 

$('section#newsletters .hide').click(function(event) { 
    event.preventDefault(); 

    var $ele = $('section#newsletters nav'); 
    var toHeight = ((toggle = !toggle) ? oldHeight : 20); 

    oldHeight = $ele.height(); 
    $ele.animate({ height: toHeight }); 

}); 

其中「20」是向上滑動時切換到的像素高度。

小提琴:http://jsfiddle.net/QV38D/

+0

這個工程請客 – Andy 2011-05-11 09:37:05

+0

謝謝大家,感謝大家的幫助... – Andy 2011-05-11 09:37:41

+0

如何默認高度?如果我使用CSS,它會修復高度... – Andy 2011-05-11 10:24:58

0

您可能需要使用animate和代碼的曲柄連桿機構自己。沿着以下線的東西:

$("section#newsletters .hide").click(function() { 
    $("section#newsletters nav").animate({ height: "100px"}, 400, 
     function() { $("section#newsletters").removeClass("hide").addClass("show"); } 
    ); 
}); 
$("section#newsletters .show").click(function() { 
    $("section#newsletters nav").animate({ height: "1000px"}, 400, 
     function() { $("section#newsletters").removeClass("show").addClass("hide"); } 
    ); 
}); 

100px1000px分別摺疊和展開列表的高度。

+0

其他內容上面坐着這樣當我點擊它,但多數民衆贊成在即時通訊猜測事做與CSS ... – Andy 2011-05-11 09:32:08

+0

展開高度也可改變......它不會永遠是1000像素 – Andy 2011-05-11 09:34:51

1

這個討論引發我找到一個幾乎相同的問題的解決方案。下面是我用過的東西,只是我相信你需要的東西。

可以使用三元運算符設置高度變量,然後在animate()上使用該變量。可以爲animate設置更多選項()我只包含高度。您可以使用相同的方法來更改顯示/隱藏文本。

$('section#newsletters .hide').click(function() { 
    $(this).text($(this).text() == 'Show' ? 'Hide' : 'Show'); 
    var height = $('section#newsletters nav').height() == '[original height]' ? '[new height]' : '[original height]'; 
    $('section#newsletters nav').animate({height:height}; 
}); 

因此,例如,如果你想從50像素去爲100px,然後回到50,你會怎麼做:

$('section#newsletters .hide').click(function() { 
    $(this).text($(this).text() == 'Show' ? 'Hide' : 'Show'); 
    var height = $('section#newsletters nav').height() == '50' ? '100' : '50'; 
    $('section#newsletters nav').animate({height:height}; 
});