单击子元素折叠div



我试图在点击子元素时折叠父div,就像下面

<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(),但这也不起作用。

这里应该做哪些更改?

试试这个:

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

演示

你的代码没有工作,因为在点击内部子div时,也点击了父div。我们已经使用event.stopPropagation()停止了这种情况,您的代码可以正常工作。

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

尝试:

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

发生这种情况是因为单击.collapse链接气泡到.expanddiv触发了展开功能。可以通过调用event.stopPropagation();

来防止冒泡
$('.collapse').on('click',function(e){
     e.stopPropagation();
     $('.expand').stop().animate({
         width: '300px',
         height:'50px'
     });
 });
http://jsfiddle.net/nvR2S/1/

最新更新