点击子元素折叠div

时间:2013-04-16 06:06:11

标签: javascript jquery html parent-child collapse

我试图在点击下面的子元素

时折叠父div

HTML

<div class="expand">
    <h3>expand this div</h3>
    <a href="#" class="collapse" style="display:none;">Collapse</a>
</div>

CSS

.expand{
    border:2px dotted green;
}

的jQuery

$('.expand').click(function(){
    $(this).stop().animate({
        width:'300px',
        height:'300px'
    });
    $('.collapse').show();
});

 $('.collapse').on('click',function(){
     $('.expand').stop().animate({
         width: '300px',
         height:'50px'
     });
 });

它不起作用,我也试过使用$(this).parent().animation(),但这也不行。

这里应该做些什么改变?

LIVE FIDDLE HERE

3 个答案:

答案 0 :(得分:2)

试试这个:

$('.collapse').on('click',function(e){
     e.stopPropagation()
     $(this).parent('.expand').stop().animate({
         width: '300px',
         height:'50px'
     });
     $(this).hide();
});

DEMO HERE

您的代码无法正常运行,因为点击内部子div时,也点击了父div。我们已使用event.stopPropagation()停止使用,您的代码运行正常。

还添加$(this).hide()以隐藏collapse点击它。

答案 1 :(得分:2)

尝试:

$('.expand').on('click', '.collapse',function(e){
 e.stopPropagation();
 $(this).hide();
 $('.expand').stop().animate({
     width: '300px',
     height:'50px'
 });
});

DEMO

答案 2 :(得分:1)

这是因为您单击.collapse链接气泡直至.expand div触发扩展功能。您可以通过调用event.stopPropagation();

来阻止冒泡
$('.collapse').on('click',function(e){
     e.stopPropagation();
     $('.expand').stop().animate({
         width: '300px',
         height:'50px'
     });
 });

http://jsfiddle.net/nvR2S/1/

相关问题