我有一个部分,在这个部分中,悬停在父div上时,我希望显示子div (元素),所以下面是
JSFIDDLE:live demo
这是HTML
<div class="flex-container">
<div class="box">1
<span class="box-children">Children Div</span>
</div>
<div class="box">2
<span class="box-children">Children Div</span>
</div>
<div class="box">3
<span class="box-children">Children Div</span>
</div>
<div class="box">4
<span class="box-children">Children Div</span>
</div>
<div class="box">5
<span class="box-children">Children Div</span>
</div>
<div class="box">6
<span class="box-children">Children Div</span>
</div>
</div>
这是JS
$(document).ready(function() {
console.log('init')
$('.box').hover(function(){
$('.box-children').addClass('open');
},
function(){
$('.box-children').removeClass('open');
});
});
期望值:
在悬停的父元素上,它应该显示子元素
不幸的是,它现在悬停着,它显示了所有的子元素
发布于 2020-10-12 21:55:22
您可以使用'mouseenter‘和'mouseleave’事件,并切换所需的CSS类来显示/隐藏子div。使用this
查找正确的子目录。
请参见下面的代码
$(document).ready(function() {
console.log('init');
//hide all children on page load
$('.box-children').addClass('close');
$('.box').on('mouseenter', function(){
$(this).find('.box-children').toggleClass('open close');
});
$('.box').on('mouseleave', function(){
$(this).find('.box-children').toggleClass('open close');
});
});
.open {display: block;}
.close {display: none;}
.box {border: 1px solid red;}
.box-children {border: 1px solid green;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="flex-container">
<div class="box">1
<span class="box-children">Children Div</span>
</div>
<div class="box">2
<span class="box-children">Children Div</span>
</div>
<div class="box">3
<span class="box-children">Children Div</span>
</div>
<div class="box">4
<span class="box-children">Children Div</span>
</div>
<div class="box">5
<span class="box-children">Children Div</span>
</div>
<div class="box">6
<span class="box-children">Children Div</span>
</div>
</div>
发布于 2020-10-12 21:45:58
您可以在回调中使用this
来引用触发器元素(在本例中为父元素):
$(document).ready(function() {
console.log('init')
$('.box').hover(function(){
$(this).find('.box-children').addClass('open');
},
function(){
$(this).find('.box-children').removeClass('open');
});
});
.box-children {
display: none;
}
.box-children.open {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="flex-container">
<div class="box">1
<span class="box-children">Children Div</span>
</div>
<div class="box">2
<span class="box-children">Children Div</span>
</div>
<div class="box">3
<span class="box-children">Children Div</span>
</div>
<div class="box">4
<span class="box-children">Children Div</span>
</div>
<div class="box">5
<span class="box-children">Children Div</span>
</div>
<div class="box">6
<span class="box-children">Children Div</span>
</div>
</div>
https://stackoverflow.com/questions/64319054
复制相似问题