【问题标题】:Targeting Only One Other Class Within the Same Parent With Jquery使用 Jquery 仅针对同一父级中的一个其他类
【发布时间】:2019-06-11 16:10:53
【问题描述】:

我试图通过悬停具有相同父级的另一个元素来仅影响一个类。有许多具有相同类名的父/元素,我只需要在每个内部定位一个即可实现悬停效果。我正在尝试使用 .find(),但由于某种原因它不起作用。如果我不使用 .find(),它会开始针对页面上的所有“.team-title”类元素。

<div class="team-parent">
  <div class="team-memeber"></div>
  <div class="team-title"></div>
</div>

<div class="team-parent">
  <div class="team-member"></div>
  <div class="team-title"></div>
</div>

<div class="team-parent">
  <!-- ... -->
</div>
$(".team-member").hover(function() {
  $("this").find(".team-title").animate({"marginLeft": "15px"}, 400);
}, function() {
  $("this").find(".team-title").animate({"marginLeft": "0px"}, 400);
});

【问题讨论】:

    标签: jquery html jquery-hover


    【解决方案1】:

    首先您需要使用this 作为关键字,而不是字符串。其次,find() 用于定位子元素,而您要定位的元素是兄弟元素,因此您可以使用 next(),如下所示:

    $(".team-member").hover(function() {
      $(this).next(".team-title").animate({
        "marginLeft": "15px"
      }, 400);
    }, function() {
      $(this).next(".team-title").animate({
        "marginLeft": "0px"
      }, 400);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="team-parent">
      <div class="team-member">Member 1</div>
      <div class="team-title">Team 1</div>
    </div>
    <div class="team-parent">
      <div class="team-member">Member 2</div>
      <div class="team-title">Team 2</div>
    </div>

    话虽如此,这里不需要 JS,因为您想要实现的目标可以在 CSS 中更有效地完成:

    .team-title {
      margin-left: 0;
      transition: margin 0.4s;
    }
    
    .team-member:hover + .team-title {
      margin-left: 15px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="team-parent">
      <div class="team-member">Member 1</div>
      <div class="team-title">Team 1</div>
    </div>
    <div class="team-parent">
      <div class="team-member">Member 2</div>
      <div class="team-title">Team 2</div>
    </div>

    【讨论】:

    • 完美运行,我最终在父类上使用了 .find() 并且一切正常。
    猜你喜欢
    • 1970-01-01
    • 2019-06-29
    • 2016-08-05
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    相关资源
    最近更新 更多