jQuery在点击和替换内容时展开DIV

时间:2012-04-22 19:06:31

标签: jquery

我正在尝试在用户点击标签页时创建可展开的卷展栏。

它基本上是2行标签,每行都有自己的颜色,当用户点击其中一个时,隐藏的DIV应该动画显示。 我不认为这很难做到,但当用户点击其他选项卡时,问题就出现了。然后新内容必须超越现有内容。

这是我到目前为止所拥有的; http://jsfiddle.net/craigzilla/W3afW/


                     The 4 images represent what should happen
                      when you click on tab 01, 02, 03 and 08  

                    



                    

2 个答案:

答案 0 :(得分:1)

jsFiddle demo

$(document).ready(function() {
    var $cont;    
    function tgl_conts(){
        $('.content').stop().animate({height: 0},1200);
        $cont.stop().animate({height:210},1200);
    }

    $('.tab').on('click',function(){
        var tabClass=$(this).attr('class').split(' ')[1];
        $cont = $('.'+tabClass+':not(.tab)');
        var h = ($cont.height() === 0) ? tgl_conts() :  ( $cont.stop().animate({height: 0},1200) );  
    });

});

小心!!!我删除了你所有的ID(也是CSS),并为你的副本添加了单独的类:

.turquoise.turquoise2
同样适用于.pink .pink2',因为每个元素都有2个元素,我们必须区分它们!

P.S:可用性很好!伟大的表达,好主意兄弟!

修改
为jQuery UI库添加了“速度”(动画时间)和缓动的设置:

demo with easing

答案 1 :(得分:0)

好的......所以基本上你要做的就是在每个标签中都有一个<div>元素。当用户单击其中一个选项卡时,jQuery将确保没有其他“弹出”div元素可见,然后显示相应的div。

我将以3个标签为例 -

<div class="tab" id="pink">
    <img src="http://placehold.it/160x160" width="160" height="160" />
    <span class="tab_text">TITLE 01</span>
    <div class="pop-out">Some pink information</div>
</div>
<div class="tab" id="turquoise">
    <img src="http://placehold.it/160x160" width="160" height="160" />
    <span class="tab_text">TITLE 02</span>
    <div class="pop-out">Some turquoise information</div>
</div>
<div class="tab" id="yellow">
    <img src="http://placehold.it/160x160" width="160" height="160" />
    <span class="tab_text">TITLE 03</span>
    <div class="pop-out">Some yellow information</div>
</div>

请注意,每次我使用id属性时,他们每个都是唯一的。 id属性应始终具有唯一值,而不是class属性,您可以看到该属性具有相同的值。 class="pop-out"

  • pop-out将是我们识别所有弹出式div元素的方法
  • 当用户点击标签时,我们会添加一个额外的sel类(已选中的简称)。这样我们就可以跟踪最后打开的div(如果有的话),并确保在打开新的div之前关闭它。

现在,假设我们希望触发器成为整个标签。用户点击它的任何地方都会触发弹出窗口。

$(".tab").on('click',function(){
  $("div.pop-out.sel").fadeOut().removeClass('sel'); // this will hide the last selected div and remove its selected class
  $(this).find("div.pop-out").fadeIn().addClass('sel'); // this will display the div of the element the user clicked and add the selected class.
}

显然你可以替换你想要的任何动画。

现在我们还可以使用 -

跟踪打开的标签
$("div.pop-out.sel").closest("div.tab");

这将返回当前显示的弹出div的父级。请记住先测试所选的div 实际是否存在:)