我试图找出如何编辑此 jQuery 代码,以便只有悬停的父级显示其子级。目前,当任何父级悬停时,都会显示所有子级。
非常感谢任何帮助。
jQuery(document).ready(function($) {
$(".parent").hover(
function () {
$(".child").addClass("hover");
},
function () {
$(".child").removeClass("hover");
}
);
});
.parent {
position:relative;
width:100px;
height:100px;
background:red;
display:inline-block;
float:left;
margin-right:6px;
}
.child {
width:inherit;
height:30px;
position:absolute;
bottom:0;
background-color:blue;
opacity:0;
transition:0.5s;
}
.child.hover {
opacity:1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
<div class="child">
</div>
</div>
<div class="parent">
<div class="child">
</div>
</div>
<div class="parent">
<div class="child">
</div>
</div>
最佳答案
您只需使用 $(this).find(".child")
来横穿直接子级,如下所示:
$(".parent").hover(
function() {
$(this).find(".child").addClass("hover");
},
function() {
$(this).find(".child").removeClass("hover");
}
);
或者,简单地使用toggleClass()
:
$(".parent").hover(function() {
$(this).find(".child").toggleClass("hover");
});
关于jquery - 如何使用 jQuery 以悬停效果定位特定父级的子级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60784873/