jQuery - 使用最近的选择器在悬停时显示和隐藏div

时间:2015-12-02 20:45:01

标签: javascript jquery html css

我试图使用jquery的hover函数在悬停时简单地实现显示/隐藏功能。

但是无法显示和隐藏特定的div。当我将鼠标悬停在当前span代码上时,我只希望隐藏当前(最近的)div,并显示最接近或下一个可能的div

但是目前由于班级名称相同,所以它显示了所有divs

FIDDLE HERE

HTML结构:

<div class="parentCat">
    <div class="imageContainer">
        <span class="hoverEffect">Some Image</span>
    </div>
    <div class="showContainer">
        <span>New Image</span>
    </div>
</div>
<div class="parentCat">
    <div class="imageContainer">
        <span class="hoverEffect">Some Image</span>
    </div>
    <div class="showContainer">
        <span>New Image</span>
    </div>
</div>

2 个答案:

答案 0 :(得分:3)

如果将事件转移到父元素,一切都会变得更简单:

$('.ca').hover(function () {
    $('.imageContainer', this).hide();
    $('.showContainer', this).show();

}, function () {
    $('.imageContainer', this).show();
    $('.showContainer', this).hide();
});

Updaated working example

答案 1 :(得分:1)

如果您需要此效果,则需要更改代码。具有悬停事件的div不能是您隐藏的那个。嵌套父div的相关div INSIDE也是一种好习惯。我相信这就是你要找的东西。

HTML

  <div class="ca hoverEffect" style="height:40%">
      <div class="imageContainer">
          <span>Some Image</span>
      </div>
      <div class="showContainer">
          <span>New Image</span>
      </div>
  </div>

JS

$('.hoverEffect').hover(function () {
    $(this).find('.imageContainer').hide();
    $(this).find('.showContainer').show();

}, function () {
    $(this).find('.imageContainer').show();
    $(this).find('.showContainer').hide();
});

Working jsfiddle