以下链接将演示我的意思。您单击第一个红色框以显示蓝色的。然后,从理论上讲,您应该能够单击绿色的小按钮再次关闭蓝色框。 它不完全符合我的要求。
$('.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>
答案 0 :(得分:1)
由于事件传播,您的子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>
答案 1 :(得分:-1)
$('.card').click(function(){
if(!$(".expand").is(":visible")){
$(this).children(".expand").show();
}
});
$('.close').click(function(e){
$(this).parent(".expand").hide();
e.stopPropagation();
});
.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>