javascript - 单击子元素折叠 div

标签 javascript html jquery parent-child

我正在尝试通过单击如下所示的子元素来折叠父 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

最佳答案

试试这个:

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

关于javascript - 单击子元素折叠 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16029874/

相关文章:

javascript - 如何列出被 ESLint 检测的文件

javascript - 如何在 Canvas 中找到填充文本的起点和终点

javascript - 我可以用 JS 禁用水平鼠标滚动吗?

javascript - 使用带有 innerHTML 的 if 语句来替换内容,我的方法不起作用......完全

javascript - flowjs : call of method `join` . 无法在混合上调用方法

javascript - 将变量传递给 slider() 中的 value 属性

html - 正确对齐表格单元格中元素之间的间距

jquery - 如何关闭 jQuery Simplemodal?

javascript - 打开后关闭切换

javascript - 如何防止 href 重定向 onclick