css 鼠标悬停时的Jquery显示each循环中具有相同类的元素

igsr9ssn  于 2023-02-10  发布在  jQuery
关注(0)|答案(1)|浏览(117)

我有三个可见元素和三个隐藏元素,我希望每次我悬停在每个元素上时,只显示一个隐藏元素。我的问题是,当我悬停在一个可见元素上时,它会显示所有三个隐藏元素,而不是一个!我使用jquery every函数,但它不起作用。我做错了什么?下面是我的代码:

$(document).ready(function(){

    $( ".thumbnail-top" ).each(function() {
        $( this ).mouseover(function(){
      $(".productImageBox-1").fadeIn('400');
      });
      $( this ).mouseout(function(){
        $(".productImageBox-1").fadeOut('400');
        });

      });

});
.thumbnail-top {
position:relative;
float:left;
margin:5px;
}

.product-thumbnail {
width:200px;
height:100px;
display:block;
padding:1rem;
color:#fff;
text-align:center;
cursor:pointer;
}

.productImageBox-0 {
background:blue;
}
.productImageBox-1 {
background:red;
position:absolute;
top:0;
left:0;
z-index:1;
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="thumbnail-top">
<a class="product-thumbnail productImageBox-0">I AM A BLUE BOX</a>
<a class="product-thumbnail productImageBox-1">NOW I AM A RED BOX</a>
</div>
</div>

<div class="thumbnail-top">
<a class="product-thumbnail productImageBox-0">I AM A BLUE BOX</a>
<a class="product-thumbnail productImageBox-1">NOW I AM A RED BOX</a>
</div>
</div>

<div class="thumbnail-top">
<a class="product-thumbnail productImageBox-0">I AM A BLUE BOX</a>
<a class="product-thumbnail productImageBox-1">NOW I AM A RED BOX</a>
</div>
</div>
pgky5nke

pgky5nke1#

您需要将选择限制为$(this)的子对象,而鼠标进入和鼠标离开可能更适合您的需要。

$(document).ready(function() {

  $(".thumbnail-top").each(function() {
    $(this).mouseenter(function() {
      $(this).find(".productImageBox-1").fadeIn('400');
    });
    $(this).mouseleave(function() {
      $(this).find(".productImageBox-1").fadeOut('400');
    });

  });

});
.thumbnail-top {
  position: relative;
  float: left;
  margin: 5px;
}

.product-thumbnail {
  width: 200px;
  height: 100px;
  display: block;
  padding: 1rem;
  color: #fff;
  text-align: center;
  cursor: pointer;
}

.productImageBox-0 {
  background: blue;
}

.productImageBox-1 {
  background: red;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="thumbnail-top">
  <a class="product-thumbnail productImageBox-0">I AM A BLUE BOX</a>
  <a class="product-thumbnail productImageBox-1">NOW I AM A RED BOX</a>
</div>

<div class="thumbnail-top">
  <a class="product-thumbnail productImageBox-0">I AM A BLUE BOX</a>
  <a class="product-thumbnail productImageBox-1">NOW I AM A RED BOX</a>
</div>

<div class="thumbnail-top">
  <a class="product-thumbnail productImageBox-0">I AM A BLUE BOX</a>
  <a class="product-thumbnail productImageBox-1">NOW I AM A RED BOX</a>
</div>

相关问题