2

好吧,你会看到我是设计师而不是程序员,所以不要对我强硬。我有一个效果很好的切换开关,但我无法启动简单的显示和隐藏脚本。我比较松……问题是带有切换功能的 H4 独立运行良好。但我还需要通过按两个按钮来显示全部并隐藏全部。

切换效果

$(function() {
    $('.toggle-item').each(function(ix, el) {

        $(this).addClass('inactive');
        var contentDiv = $('.toggle-content', $(el));
        $(this).attr('data-height', contentDiv.outerHeight());
        contentDiv.css('overflow', 'hidden');
        contentDiv.height(0);
    });

    $(".toggle-item h4").click(function(){
        var $parent = $(this).parent('.toggle-item');
        if($parent.length) {
            if( $parent.hasClass('inactive') ) {
                $parent.removeClass('inactive');
                $('.toggle-content', $parent).height(           $parent.attr('data-height'));
            } else {
                $parent.addClass('inactive');
                $('.toggle-content', $parent).height( 0 );
            }
        }
    });
});

HTML 代码:

<div class="toggle-item">
    <h4>SOME TEXT AS HEADLINE</h4>
    <div class="toggle-content">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras accumsan, turpis facilisis ultricies consequat, tellus ligula sagittis libero, porttitor venenatis urna dui non quam. Fusce aliquam, libero sed eleifend pellentesque, ligula dolor porta neque, et egestas diam mauris id odio.</p>
    </div>
</div>

按钮

<button id="show">Show All</button> 
<button id="hide">Hide All</button> 

意图

$(document).ready(function(){
  $("#show").click( function() {
       $('.toggle-content').show();
  });
  $("#hide").click(function(){
       $('.toggle-content').hide();
  });
});

在这里您可以找到正在运行的示例。

欢迎任何提示!TIA。

4

2 回答 2

0

我认为您需要这个,只需尝试将您的脚本更新为如下:

  $("#show").click( function() {
       $('.toggle-content').each(function(){
         // you need this because height goes to 0pt
         $(this).height('auto');
         $(this).show();
       });
  });
  $("#hide").click(function(){
       $('.toggle-content').each(function(){
         $(this).hide();
       });
  });

我希望这会有所帮助

于 2012-08-10T09:39:31.093 回答
0

好吧,通过来自 Tiendy.com 的 Manuel Cebrian 先生的诀窍:

$(document).ready(function(){

  $("#show").click( function() {
       $('.toggle-item').each(function(i) {             
            $(this).removeClass('inactive');
            $('.toggle-content', this).height( $(this).attr('data-height'));
       });
  });

  $("#hide").click(function(){
       $('.toggle-item').each(function(i) {
            $(this).addClass('inactive');
            $('.toggle-content', this).height( 0 );
       });
  });

});

这将打开和关闭所有,一些打开的也会关闭。非常感谢 Cebrian 先生,希望这能帮助更多人。谢谢大家。

于 2012-08-11T12:18:26.400 回答