1

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

但是,如果我将鼠标悬停在链接上,然后将鼠标移到页面的另一部分(而不是 div)上,则 div 在应该关闭时保持打开状态,并且仅当我将鼠标移到 div 上时触发 mouseleave 事件时才会关闭然后关闭 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

4 回答 4

3

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

我添加了一个淡出效果,因为你有额外的时间。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>

于 2018-10-31T22:09:06.047 回答
0

我想我明白你想要做什么。解决该问题的方法是监听链接上的悬停事件和鼠标离开事件。悬停事件将确保当鼠标移过链接时显示 div,然后鼠标离开事件将确保当鼠标离开链接时 div 消失,但当然你也会同时听悬停事件和 div 本身的鼠标离开事件,悬停事件将确保 div 仍在显示,而鼠标离开事件将确保 div 一旦鼠标离开它就会消失。

//add this to the original code
$("#Shop").mouseleave(function () {
        $("#productList ").hide();
}),
于 2018-10-31T22:36:41.957 回答
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>

于 2018-10-31T22:06:05.320 回答
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>

于 2018-10-31T22:07:19.170 回答