【问题标题】:Collapse div on click of child element单击子元素时折叠 div
【发布时间】:2013-04-08 10:26:05
【问题描述】:

我试图在点击下面的子元素时折叠父 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

【问题讨论】:

    标签: javascript jquery html parent-child collapse


    【解决方案1】:

    试试这个:

    $('.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

    【讨论】:

      【解决方案3】:

      发生这种情况是因为您单击.collapse 链接冒泡到.expand div 触发了展开功能。你可以通过调用event.stopPropagation();来防止冒泡

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-20
        • 2015-10-03
        • 2022-01-09
        • 1970-01-01
        • 1970-01-01
        • 2013-05-31
        • 1970-01-01
        • 2020-02-01
        相关资源
        最近更新 更多