jquery - 如何使用 jQuery 以悬停效果定位特定父级的子级?

标签 jquery html css

我试图找出如何编辑此 jQuery 代码,以便只有悬停的父级显示其子级。目前,当任何父级悬停时,都会显示所有子级。

非常感谢任何帮助。

jsFiddle

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");
  }
);  

DEMO

或者,简单地使用toggleClass():

$(".parent").hover(function() {
   $(this).find(".child").toggleClass("hover");
});

DEMO

关于jquery - 如何使用 jQuery 以悬停效果定位特定父级的子级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60784873/

相关文章:

jquery - 阻止 body 滚动的更好方法?

父框架的 PHP header 位置更改

python - 如何循环遍历标签并重定向以检索更多标签?

html - float 和堆叠上下文

html - 如何在鼠标移开时暂停视频?

css - 如何在 JSF 中动态添加 css 样式属性

jquery - 如果类不可见,则 HTML 显示元素

php - jquery函数中处理单引号和双引号

javascript - 如何检测jQuery中是否滚动了特定元素或div?

c# - .NET MVC 的 jQuery getJSON 不工作