如何让Bootstrap4的下拉菜单支持悬停和点击两种方式调出
Bootstrap的类似问题还有:
注意,本页内容仅适用于Bootstrap4,未在更早版本做过测试。
JS核心内容:
$( ".dropdown-menu" ).css('margin-top',0); $( ".dropdown" ) .mouseover(function() { $( this ).addClass('show').attr('aria-expanded',"true"); $( this ).find('.dropdown-menu').addClass('show'); }) .mouseout(function() { $( this ).removeClass('show').attr('aria-expanded',"false"); $( this ).find('.dropdown-menu').removeClass('show'); });
HTML结构
<ul class="nav nav-pills"> <li class="nav-item"> <a class="nav-link active uppercase" href="#">Home</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle uppercase outline" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Pages</a> <div class="dropdown-menu"> <a class="dropdown-item uppercase aboutUs" href="#">About us</a> <a class="dropdown-item uppercase" href="#">Company</a> <a class="dropdown-item uppercase" href="#">Our process</a> <a class="dropdown-item uppercase" href="#">Services</a> <a class="dropdown-item uppercase" href="#">Contact us</a> <a class="dropdown-item uppercase FAQ" href="#">F.A.Q.</a> </div> </li> </ul>
另外如果想让菜单超链接生效可以用下面代码实现:
首先你要在连接的文本外加一个容器如<span class='nav-parent'>
$(document).on("click",".nav-parent",function() { var $url = $(this).closest("a.nav-link").attr("href"); console.log($url); location.href = $url; return false; });