在悬停和mouseenter上显示div,但当鼠标不在目标或div上时隐藏

时间:2018-10-31 21:41:30

标签: jquery html

我有一个问题,当悬停在链接上时会显示一个div,然后悬停在div上时它会保持打开状态。

但是,如果我将鼠标悬停在链接上,然后将鼠标移到页面的另一部分(而不是div)上,则div在应关闭时保持打开状态,并且仅当在将鼠标移至该位置上触发mouseleave事件时才关闭div,然后离开div。

有人可以帮助解决这个问题吗?

$(document).ready(function() {
  $(".showProducts").hide();

  $("#Shop").hover(function() {
      $("#productList ").show();
    }),
    $(".showProducts").mouseenter(function() {
      $("#productList ").show();
    });
  $(".showProducts").mouseleave(function() {
    $(" #productList").hide();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="Shop" name="Shop" class="nav-link" href="/shop/">Shop</a>

<div id="productList" class="container showProducts">productList</div>

4 个答案:

答案 0 :(得分:1)

为此,我建议使用一种称为“反跳”的技术。基本上,它只是引入了一个小的计时器来删除可见区域。每次鼠标进入这些区域之一时,请清除计时器。当它离开时,启动它。在计时器结束时,删除内容。

我添加了一个淡出效果,因为您有更多时间。 450毫秒的延迟基于用户的平均鼠标移动。背景颜色仅仅是为了让我们更清楚地看到我们所关注的内容区域在哪里。

$(document).ready(function() {
  $(".showProducts").hide();
  
  var timer;
  function debounce(){
      clearTimeout(timer);
      timer = setTimeout(function(){
          $("#productList").fadeOut('fast');
      },450);
  }
  
  $("#Shop").hover(function() {
      // hover over
      $("#productList").show();
      clearTimeout(timer);
    },function(){
      // hover out
      debounce();
    });
  $(".showProducts").mouseenter(function(){
    clearTimeout(timer);
  });
  $(".showProducts").mouseleave(function(){
    debounce();
  });
});
#Shop{
 background-color: lightgrey;
}

#productList{
 background-color: beige;
 width:50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a id="Shop" name="Shop" class="nav-link" href="/shop/">Shop</a>

<div id="productList" class="container showProducts">productList</div>

答案 1 :(得分:0)

CSS解决方案怎么样?这个使用next (+)选择器...

a,
div {
  border: 1px solid red;
}

.showProducts {
  display: none;
}

#Shop:hover+div.showProducts {
  display: block;
}

div.showProducts:hover {
  display: block;
}
<a id="Shop" name="Shop" class="nav-link" href="/shop/">Shop</a>

<div id="productList" class="container showProducts">productList</div>

答案 2 :(得分:0)

您不需要jQuery-CSS可以使用同级组合器(如果有多个同级,则可以使用直接同级组合器(+)定位下一个元素,也可以使用常规同级组合器(〜)。元素。

#productList {display: none}
#Shop:hover + #productList {display: block}
#productList:hover {display: block}
<a id="Shop" name="Shop" class="nav-link" href="/shop/">Shop</a>

<div id="productList" class="container showProducts">productList</div>

答案 3 :(得分:0)

我想我了解您正在尝试做什么。解决该问题的方法是侦听链接上的悬停事件和鼠标离开事件。悬停事件将确保当鼠标移到链接上时显示div,然后鼠标离开事件将确保当鼠标离开链接时div消失,但是您当然也要同时聆听在div本身上有一个悬停事件和一个鼠标离开事件,该悬停事件将确保div仍在显示,而鼠标离开事件将确保div一旦鼠标离开它就会消失。

//add this to the original code
$("#Shop").mouseleave(function () {
        $("#productList ").hide();
}),