Bootstrap 4 Dropdown 鼠标点击改为鼠标悬停触发

Bootstrap 4 导航栏(navbar),支持二级菜单,由 Dropdown 实现,但默认为单击事件展开二级菜单,但很多需求是鼠标悬浮就需要展开子菜单。下面是方案:

CSS

.dropdown:hover>.dropdown-menu {
    display: block;
}

.dropdown>.dropdown-toggle:active {
    pointer-events: none;
}

有个小 Bug 顶级菜单和子菜单之间有一点空隙,鼠标移动到空隙后菜单就隐藏了。我们再修改 dropdown-menu 的样式,加一个 mt-0 的样式就没有空隙了。

HTML

<ul class="navbar-nav mr-auto">
    <li class="nav-item active">
        <a class="nav-link active" href="/">DevDoc</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="/linux">Linux</a>
    </li>
    <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" href="/spring">Spring</a>
        <div class="dropdown-menu mt-0" aria-labelledby="navbarDropdown">
            <a class="dropdown-item" href="/spring-data">Spring Data</a>
            <a class="dropdown-item" href="/spring-boot">Spring Boot</a>
            <a class="dropdown-item" href="/spring-cloud">Spring-Cloud</a>
        </div>
    </li>
    <li class="nav-item"><a class="nav-link" href="/docker">Docker</a></li>
    <li class="nav-item"><a class="nav-link" href="/mysql">MySQL</a></li>
</ul>

2019-10-11 Bootstrap, dropdown