首页 > 解决方案 > 打开后如何使用 jQuery 关闭/隐藏此 div?

问题描述

以下链接将说明我的意思。您单击第一个红色框以显示蓝色框。然后,理论上,您应该可以再次单击绿色小按钮关闭蓝色框。它并不完全按照我想要的方式工作。

$('.card').click(function(){
	if($(".expand").is(":visible")){
	} else {
		$(this).children(".expand").show();
	}
});

$('.close').click(function(){
  $(this).parent(".expand").hide();
});
.card {
  height: 256px;
  width: 256px;
  background-color: red;
  }
  
.expand {
  display: none;
  position: relative;
  height: 256px;
  width: 256px;
  left: 256px;
  background-color: blue;
  }
  
.close {
  margin: 16px;
  position: absolute;
  height: 16px;
  width: 16px;
  background-color: green;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">
  <div class="expand">
    <div class="close">
    </div>
  </div>
</div>

标签: jqueryhtmlcss

解决方案


由于事件传播,您的子 div 也会触发父函数。

您需要使用停止传播:e.stopPropagation()

$('.card').click(function(){
    if(!$(".expand").is(":visible")){
	$(this).children(".expand").toggle();
    }
});

$('.close').click(function(e){
    e.stopPropagation()
    $(this).parents('.expand').toggle();
});
.card {
  height: 256px;
  width: 256px;
  background-color: red;
  }
  
.expand {
  display: none;
  position: relative;
  height: 256px;
  width: 256px;
  left: 256px;
  background-color: blue;
  }
  
.close {
  margin: 16px;
  position: absolute;
  height: 16px;
  width: 16px;
  background-color: green;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">
  <div class="expand">
    <div class="close">
    </div>
  </div>
</div>


推荐阅读