【问题标题】:How to only show hover on div with same class name, but only on current div如何仅在具有相同类名的 div 上显示悬停,但仅在当前 div 上显示
【发布时间】:2022-01-21 17:41:40
【问题描述】:

所以我试图在现有 div 上显示一个隐藏的 div,但只显示鼠标悬停的 div。我有一个显示错误的jsfiddle。悬停时,它会显示所有未隐藏的 div,但我只希望当前 div 可见,而不是全部可见。

风格:

  background-color: blue;
  color: red;
  width: 100px;
  height: 100px;
  position: relative;
}
.productHover{
      position: absolute;
      top: 20px;
      left: 0;
      width: 100%;
      height: 100%;
      display: none;
      color: white;
}

HTML:

Apple
  <div class="productHover">
    0.1%
  </div>
</div>

<div class="product">
Apple2
  <div class="productHover">
    0.2%
  </div>
</div>

<div class="product">
Apple3
  <div class="productHover">
    0.3%
  </div>
</div>

jquery:

    function() {
        $('.productHover').show();
    }, function() {
        $('.productHover').hide();
    }
 );

jsfiddle:https://jsfiddle.net/spaLo6zf/12/

这些 div 具有相同的类名,我试图一次只显示一个 productHover,现在同时显示。

【问题讨论】:

    标签: jquery


    【解决方案1】:

    将您的 jQuery 更改为:

    $('.product').hover(
      function() {
        $(this).find('.productHover').show();
      },
      function() {
        $(this).find('.productHover').hide();
      }
    );
    .product {
      background-color: blue;
      color: red;
      width: 100px;
      height: 100px;
      position: relative;
    }
    
    .productHover {
      position: absolute;
      top: 20px;
      left: 0;
      width: 100%;
      height: 100%;
      display: none;
      color: white;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="product">
      Apple
      <div class="productHover">
        0.1%
      </div>
    </div>
    
    <div class="product">
      Apple2
      <div class="productHover">
        0.2%
      </div>
    </div>
    
    <div class="product">
      Apple3
      <div class="productHover">
        0.3%
      </div>
    </div>

    【讨论】:

    • 谢谢您,这非常有效。我以为我尝试过这个或类似的东西,但我认为我的语法有点不对劲。干杯。
    猜你喜欢
    • 1970-01-01
    • 2012-01-27
    • 2014-07-19
    • 2012-03-03
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    相关资源
    最近更新 更多