将鼠标悬停在空的孩子上时显示父图像

首先,我检查并尝试了所有儿童悬停效果的父级,但找不到能够解决我今天要解决的问题的任何方法。

基本上,我只想在悬空的孩子时显示父图像,而不是在孩子有图像时才显示。

The markup is as follows and a codepen is available here https://codepen.io/cr8tivly/pen/LYpXVGx

谢谢

的HTML

<div class="container mx-auto position-relative">
  <ul class="main-menu col-6">
    <li class="nav-item">
      <a href="">menu-1</a>
      <div class="parent-image">
        <img class="main-image" src="http://placehold.it/150/f91?text=Parent-1" alt="" />
      </div>
      <ul class="dd-menu">
        <li class="nav-item">
          <a href="">smenu-1</a>
          <div class="child-image">
            <img class="" src="http://placehold.it/100/ggd" alt="" />
          </div>
        </li>

        <li class="nav-item">
          <a href="">smenu-2</a>
          <div class="child-image">
            <img class="" src="http://placehold.it/100/cdd" alt="" />
          </div>
        </li>
        <li class="nav-item">
          <a href="">smenu-3</a>
          <div class="child-image"></div>
        </li>
      </ul>
    </li>
    <li class="nav-item">
      <a href="">menu-2</a>
      <div class="parent-image">
        <img class="main-image" src="http://placehold.it/150/green?text=Parent-2" alt="" />
      </div>
      <ul class="dd-menu">
        <li class="nav-item">
          <a href="">smenu-1</a>
          <div class="child-image">
            <img class="" src="http://placehold.it/100/e00" alt="" />
          </div>
        </li>
        <li class="nav-item">
          <a href="">smenu-2</a>
          <div class="child-image">
            <img class="" src="http://placehold.it/100/dbb" alt="" />
          </div>
        </li>
        <li class="nav-item">
          <a href="">smenu-3</a>
          <div class="child-image"></div>
        </li>
      </ul>
    </li>
  </ul>
</div>

jQuery查询

$('.parent-image').hide();
$('.nav-item').hover(
  function(){
  $(this).find('.parent-image').show();
  },
  function() {
    $(this).find('.parent-image').last().hide();
  }
);

$('.child-image').hide();
$('.dd-menu .nav-item').hover(
  function(){
  $(this).find('.child-image').show();
   $(this).find('.child-image:empty', function(){
   $('.parent-image').show();
   })

  },
  function() {
    $(this).find('.child-image').last().hide();
  }
);

的CSS

.parent-image,
.child-image {
  position: absolute;
  right: 0;
  top: 0;
}
评论