为什么我的悬停按钮下拉菜单在我鼠标悬停时不保持打开状态

Why does my hover button dropdown not stay open when I mouse-over?

本文关键字:悬停 状态 鼠标 按钮 我的 下拉菜单 为什么      更新时间:2023-09-26

首先要做的是:http://jsfiddle.net/9L81kfah/

我有一个 Bootstrap 下拉菜单,如果有人将鼠标悬停超过 200 毫秒,它应该打开并保持打开状态,特别是如果他们然后将鼠标移到菜单内容上,但它不会保持打开状态。我在这里做错了什么?

这是下拉代码:

<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
    Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
  </ul>
</div>

和jQuery:

jQuery('#dropdownMenu1').hover(function() {
        jQuery(this).next('.dropdown-menu').stop(true, true).delay(200).fadeIn();
}, function() {
        jQuery(this).next('.dropdown-menu').stop(true, true).delay(200).fadeOut();
});

这是因为您的悬停处理程序位于按钮元素上,一旦您将鼠标悬停在菜单元素上,"mouseout"处理程序就会触发,因为您离开了按钮。相反,您的处理程序应该位于周围的 .dropdown 元素上。

$('.dropdown').hover(function () {
  $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn();
}, function () {
  $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut();
});

现在,当您悬停按钮时,它将起作用,因为该按钮是.dropdown元素的子元素,并且悬停事件通过父元素向上冒泡。当您将鼠标从按钮移动到下拉菜单时,您仍将悬停在.dropdown上,因为菜单也是.dropdown的子菜单。只有当您完全离开父元素时,"mouseout"处理程序才会触发。

http://jsfiddle.net/1xpLm4jw/

您告诉下拉列表在鼠标离开按钮后淡出。相反,您应该告诉它在鼠标离开整个下拉组后淡出。

jQuery('#dropdownMenu1').hover(function() {
        jQuery(this).next('.dropdown-menu').stop(true, true).delay(200).fadeIn();
});
jQuery('.dropdown').on("mouseout", function() {
        jQuery('.dropdown-menu').stop(true, true).delay(200).fadeOut();
});

你需要有一个计时器来让它工作。仅当鼠标不在dropdown上时触发淡出。简单地说,你可以使用的组合 mouseovermouseout事件。

var timeout;
jQuery('.dropdown').on('mouseover', function () {
    clearInterval(timeout);
    jQuery('.dropdown-menu', this).stop(true, true).delay(200).fadeIn();
});
jQuery('.dropdown').on('mouseout', function () {
    var thisView = this;
    timeout = setTimeout(function () {
        jQuery('.dropdown-menu', thisView).stop(true, true).delay(200).fadeOut();
    }, 200);
});

检查小提琴