我正在尝试通过单击如下所示的子元素来折叠父 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()
,但这也不起作用。
这里应该做哪些改变?
最佳答案
试试这个:
$('.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
。
关于javascript - 单击子元素折叠 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16029874/