我有一个Twitter Bootstrap下拉菜单。正如所有Twitter Bootstrap用户所知,单击(甚至在其中单击)时,关闭菜单。
为避免这种情况,我可以轻松地在下拉菜单上附加一个click事件处理程序,只需添加著名的即可event.stopPropagation()。
event.stopPropagation()
<ul class="nav navbar-nav"> <li class="dropdown mega-dropdown"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-list-alt"></i> Menu item 1 <span class="fa fa-chevron-down pull-right"></span> </a> <ul class="dropdown-menu mega-dropdown-menu"> <li> <div id="carousel" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-slide-to="0" data-target="#carousel"></li> <li class="active" data-slide-to="1" data-target="#carousel"></li> </ol> <div class="carousel-inner"> <div class="item"> <img alt="" class="img-rounded" src="img1.jpg"> </div> <div class="item active"> <img alt="" class="img-rounded" src="img2.jpg"> </div> </div> <a data-slide="prev" role="button" href="#carousel" class="left carousel-control"> <span class="glyphicon glyphicon-chevron-left"></span> </a> <a data-slide="next" role="button" href="#carousel" class="right carousel-control"> <span class="glyphicon glyphicon-chevron-right"></span> </a> </div> </li> </ul> </li> </ul>
但是,这看起来很简单,而且是非常普遍的行为,而且由于carousel-controls(以及carousel indicators)事件处理程序都委派给了document对象,因此click这些元素(上 一个/下一个 控件,…)上的事件将被“忽略”。
carousel-controls
carousel indicators
document
click
$('ul.dropdown-menu.mega-dropdown-menu').on('click', function(event){ // The event won't be propagated up to the document NODE and // therefore delegated events won't be fired event.stopPropagation(); });
由于以下原因,不能依靠Twitter Bootstrap下拉列表hide/ hidden事件来解决:
hide
hidden
flag
删除数据属性data-toggle="dropdown"并实现下拉菜单的打开/关闭可能是一种解决方案。
data-toggle="dropdown"
首先,通过单击链接来打开/关闭下拉菜单,如下所示:
$('li.dropdown.mega-dropdown a').on('click', function (event) { $(this).parent().toggleClass('open'); });
然后听下拉菜单外的点击以将其关闭,如下所示:
$('body').on('click', function (e) { if (!$('li.dropdown.mega-dropdown').is(e.target) && $('li.dropdown.mega-dropdown').has(e.target).length === 0 && $('.open').has(e.target).length === 0 ) { $('li.dropdown.mega-dropdown').removeClass('open'); } });