如何使用jQuery实现hover效果来选中特定父元素的子元素?

3
我正在尝试找出如何编辑这段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>

4个回答

2
通过将上下文作为第二个参数传递

选择器上下文
默认情况下,选择器从文档根开始在DOM中执行搜索。但是,可以使用可选的第二个参数将替代上下文用于搜索。

https://api.jquery.com/jQuery/#jQuery1

jQuery(document).ready(function($) {

  $(".parent").hover(
    function() {
      $(".child", this).addClass("hover");
    },
    function() {
      $(".child", this).removeClass("hover");
    }
  );

});

工作演示

https://jsfiddle.net/aswinkumar863/a4sxc1up/


CSS纯解决方案

.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;
}

.parent:hover .child {
  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>


2

您只需要使用$(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");
});

演示


1
使用 $(this).find(".child").addClass("hover");
jQuery(document).ready(function($) {    

$(".parent").hover(
  function () {
    $(this).find(".child").addClass("hover");
  },
  function () {
    $(".child").removeClass("hover");
  }
);

});

1
你需要将你的代码更改为以下内容:

你需要这样改代码:

    jQuery(document).ready(function($) {    

    $(".parent").hover(
  function (e) {
    $(e.currentTarget).find(".child").addClass("hover");
  },
  function (e) {
    $(e.currentTarget).find(".child").removeClass("hover");
  }
);

});

1
当你在这个上下文中使用this时,事件的用途是什么?请解释一下。 - Shiladitya
你问题的最佳和完整答案可以在这个回答中找到:https://dev59.com/WWct5IYBdhLWcg3wc9Ig#21667010 - sajadre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接