我想有我的引导菜单自动下拉悬停,而不是必须点击菜单标题。我还想去掉菜单标题旁边的小箭头。


当前回答

<!DOCTYPE html> <html> <head> <style> .dropbtn { background-color: #4CAF50; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover {background-color: #f1f1f1} .dropdown:hover .dropdown-content { display: block; } .dropdown:hover .dropbtn { background-color: #3e8e41; } </style> </head> <body> <h2>Hoverable Dropdown</h2> <p>Move the mouse over the button to open the dropdown menu.</p> <div class="dropdown"> <button class="dropbtn">Dropdown</button> <div class="dropdown-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> </div> </body> </html>

其他回答

引导版本4和5解决方案。(兼容)

这些都是使用mouseover和mouseleave事件和一些屏幕宽度检查的完整解决方案。这比纯CSS解决方案更好。

Bootstrap v5 -纯JS(用于webpack)

export class BootstrapOpenMenuHover {

/**
 * Constructor.
 */
constructor() {
  this.windowWidth = window.innerWidth;
  this.mobileBreakPoint = 991; // Put your menu break point here, when it switches to a hamburger icon.
  this.dropdownNavItems = document.querySelectorAll(".dropdown-toggle.nav-link");
  this.dropdownMenuItems = document.querySelectorAll(".dropdown-menu");

  this.setEventListeners();
}

/**
 * Set all of our event listeners.
 */
setEventListeners() {
  const _self = this;

  // To be safe set the width once the dom is loaded.
  window.addEventListener('load',  function () {
    _self.windowWidth = window.innerWidth;
  });

  // Keep track of the width in the event of a resize.
  window.addEventListener('resize',  function () {
    _self.windowWidth = window.innerWidth;
  });

  // Bind our hover events.
  if (_self.dropdownNavItems !== null)  {
    for (let i = 0; i < _self.dropdownNavItems.length; i++) {

      // On mouse enter.
      _self.dropdownNavItems[i].addEventListener('mouseenter', function () {
        if (_self.windowWidth >= _self.mobileBreakPoint) {
          this.classList.add('show');
          this.ariaExpanded = true;
          this.dataset.bsToggle = null;

          // Update the .dropdown-menu
          this.nextElementSibling.classList.add('show');
          this.nextElementSibling.dataset.bsPopper = 'none';
        }
      });

      // On mouse leave.
      _self.dropdownNavItems[i].addEventListener('mouseleave', function () {
        if (_self.windowWidth >= _self.mobileBreakPoint) {
          this.classList.remove('show');
          this.ariaExpanded = false;
          this.dataset.bsToggle = 'dropdown';

          // Update the .dropdown-menu
          this.nextElementSibling.classList.remove('show');
          this.nextElementSibling.dataset.bsPopper = null;
        }
      });
    }
  }

  // Bind events to .dropdown-menu items.
  if (_self.dropdownMenuItems !== null) {
    for (let i = 0; i < _self.dropdownMenuItems.length; i++) {
      // On mouse enter.
      _self.dropdownMenuItems[i].addEventListener('mouseenter', function () {
        if (_self.windowWidth >= _self.mobileBreakPoint) {
          this.classList.add('show');
          this.dataset.bsPopper = 'none';

          // Update the .dropdown-toggle
          this.previousElementSibling.classList.add('show');
          this.previousElementSibling.ariaExpanded = true;
          this.previousElementSibling.dataset.bsToggle = null;
        }
      });

      // On mouse leave.
      _self.dropdownMenuItems[i].addEventListener('mouseleave', function () {
        if (_self.windowWidth >= _self.mobileBreakPoint) {
          this.classList.remove('show');
          this.dataset.bsPopper = null;

          // Update the .dropdown-toggle
          this.previousElementSibling.classList.remove('show');
          this.previousElementSibling.ariaExpanded = false;
          this.previousElementSibling.dataset.bsToggle = 'dropdown';
        }
      });
    }
   }
  }
 }

 const bootstrapOpenMenuHover = new BootstrapOpenMenuHover();

Bootstrap v4方案

这将允许您遵循顶级导航链接。

这是基于桌面和移动平台设计的。随意更改BREAK_POINT变量以满足您的需要:D。

jQuery

var WINDOW_WIDTH;
var BREAK_POINT = 991;

(function ($) {

    /** Set window width onload */
    WINDOW_WIDTH = $(window).width(); // Returns width of browser viewport
    /** Set window width if the browser is resized */
    $(window).resize(function () {
        WINDOW_WIDTH = $(window).width(); // Returns width of browser viewport
    });

    /** Dropdown menu on mouseenter */
    $(".nav-item.dropdown").on('mouseenter', function () {
        console.log("mouseenter");
        if (WINDOW_WIDTH >= BREAK_POINT) {
            // Open up the dropdown
            $(this).addClass('show'); // add the class show to the li parent
            $(this).children('.nav-link').removeAttr('data-toggle'); // remove the data-toggle attribute so we can click and follow link
            $(this).children('.dropdown-menu').addClass('show'); // add the class show to the dropdown div sibling
        }
    });
    /** Dropdown menu on mouseleave */
    $(".nav-item.dropdown").on('mouseleave', function () {
        console.log("mouseleave");
        if (WINDOW_WIDTH >= BREAK_POINT) {
            // Close the dropdown
            $(this).removeClass('show'); // add the class show to the li parent
            $(this).children('.nav-link').attr('data-toggle', 'dropdown'); // remove the data-toggle attribute so we can click and follow link
            $(this).children('.dropdown-menu').removeClass('show'); // add the class show to the dropdown div sibling
        }
    });
});

CSS

@media(min-width:  768px) {
  .dropdown-menu {
    margin-top: 0; // fixes closing on slow mouse transition
  }
}

我已经发布了一个Bootstrap 3下拉悬停功能的插件,在这个插件中,你甚至可以定义点击下拉切换元素时发生的事情(点击可以被禁用):

https://github.com/istvan-ujjmeszaros/bootstrap-dropdown-hover


既然已经有很多解了,我为什么要做这个?

我对所有之前存在的解决方案都有问题。简单的CSS没有在.dropdown上使用.open类,所以当下拉可见时,下拉切换元素上没有反馈。

js的那些干扰点击.dropdown-toggle,所以下拉菜单显示在悬停,然后隐藏它时,点击一个打开的下拉菜单,移动鼠标将触发下拉菜单再次显示。一些js解决方案破坏了iOS的兼容性,一些插件不能在支持触摸事件的现代桌面浏览器上工作。

这就是为什么我只使用标准的Bootstrap javascript API来防止所有这些问题的Bootstrap下拉悬停插件,没有任何hack。甚至Aria属性在这个插件中也工作得很好。

在我看来,最好的办法是这样的:

;(function($, window, undefined) {
    // Outside the scope of the jQuery plugin to
    // keep track of all dropdowns
    var $allDropdowns = $();

    // If instantlyCloseOthers is true, then it will instantly
    // shut other nav items when a new one is hovered over
    $.fn.dropdownHover = function(options) {

        // The element we really care about
        // is the dropdown-toggle's parent
        $allDropdowns = $allDropdowns.add(this.parent());

        return this.each(function() {
            var $this = $(this),
                $parent = $this.parent(),
                defaults = {
                    delay: 500,
                    instantlyCloseOthers: true
                },
                data = {
                    delay: $(this).data('delay'),
                    instantlyCloseOthers: $(this).data('close-others')
                },
                settings = $.extend(true, {}, defaults, options, data),
                timeout;

            $parent.hover(function(event) {

                // So a neighbor can't open the dropdown
                if(!$parent.hasClass('open') && !$this.is(event.target)) {
                    return true;
                }

                if(settings.instantlyCloseOthers === true)
                    $allDropdowns.removeClass('open');

                window.clearTimeout(timeout);
                $parent.addClass('open');
            }, function() {
                timeout = window.setTimeout(function() {
                    $parent.removeClass('open');
                }, settings.delay);
            });

            // This helps with button groups!
            $this.hover(function() {
                if(settings.instantlyCloseOthers === true)
                    $allDropdowns.removeClass('open');

                window.clearTimeout(timeout);
                $parent.addClass('open');
            });

            // Handle submenus
            $parent.find('.dropdown-submenu').each(function(){
                var $this = $(this);
                var subTimeout;
                $this.hover(function() {
                    window.clearTimeout(subTimeout);
                    $this.children('.dropdown-menu').show();

                    // Always close submenu siblings instantly
                    $this.siblings().children('.dropdown-menu').hide();
                }, function() {
                    var $submenu = $this.children('.dropdown-menu');
                    subTimeout = window.setTimeout(function() {
                        $submenu.hide();
                    }, settings.delay);
                });
            });
        });
    };

    $(document).ready(function() {
        // apply dropdownHover to all elements with the data-hover="dropdown" attribute
        $('[data-hover="dropdown"]').dropdownHover();
    });
})(jQuery, this);

样本的标记:

<li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-delay="1000" data-close-others="false">
        Account <b class="caret"></b>
    </a>
    <ul class="dropdown-menu">
        <li><a tabindex="-1" href="#">My Account</a></li>
        <li class="divider"></li>
        <li><a tabindex="-1" href="#">Change Email</a></li>
        <li><a tabindex="-1" href="#">Change Password</a></li>
        <li class="divider"></li>
        <li><a tabindex="-1" href="#">Logout</a></li>
    </ul>
</li>

为了加强Sudharshan的回答,我将其包装在一个媒体查询中,以防止在XS显示宽度上出现悬停……

@media (min-width:768px)
{
    ul.nav li.dropdown:hover > ul.dropdown-menu {
        display: block;    
    }

    .nav .dropdown-menu {
        margin-top: 0;
    }
}

标记中的插入符号也不是必需的,只是li的下拉类。

用这个脚本覆盖bootstrap.js。

jQuery(document).ready(function ($) {
$('.navbar .dropdown').hover(function() {
    $(this).addClass('extra-nav-class').find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
}, function() {
    var na = $(this)
    na.find('.dropdown-menu').first().stop(true, true).delay(100).slideUp('fast', function(){ na.removeClass('extra-nav-class') })
});

$('.dropdown-submenu').hover(function() {
    $(this).addClass('extra-nav-class').find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
}, function() {
    var na = $(this)
    na.find('.dropdown-menu').first().stop(true, true).delay(100).slideUp('fast', function(){ na.removeClass('extra-nav-class') })
});

});