2013-04-16 50 views
1

我试图瓦解父DIV的子元素的点击如下图所示倒塌的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

回答

2

试试这个:

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

DEMO HERE

您的代码并没有因为内子divdiv也被点击的点击工作。我们已经停止使用event.stopPropagation(),你的代码工作正常。

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

+0

+1谢谢,这真是棒极了。一些有答案的描述将在未来帮助某人。 –

+0

很高兴帮助! –

+0

很高兴看到补充说明。它肯定会帮助别人。 –

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/

+0

+1对于很好的解释。谢谢。 –

2

防止起泡尝试:

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

DEMO

+0

+1它也很好。 –