我正在使用这个小脚本来创建带有子链接的水平菜单。我一切正常,但有一个小障碍,那就是当单击另一个子菜单时,我需要关闭子菜单。你可以在这里看到我的菜单,我需要它,这样如果你点击菜单一,然后点击菜单二,那么菜单一子链接就会消失。
这是菜单的jQuery:
$(function() {
// Dropdown toggle
$('.dropdown-toggle').click(function(){
$(this).next('.dropdown').toggle();
});
$(document).click(function(e) {
var target = e.target;
if (!$(target).is('.dropdown-toggle') && !$(target).parents().is('.dropdown-toggle')) {
$('.dropdown').hide();
}
});
});
您需要添加:
$('.dropdown').css('display', 'none');
因此,在下一个子菜单打开之前,它会关闭当前打开的所有子菜单。法典:
// Dropdown toggle
$('.dropdown-toggle').click(function(){
$('.dropdown').css('display', 'none'); //New code
$(this).next('.dropdown').toggle();
});
您可以设置每次单击将从所有 .drop-down-items 中删除 Class .active,然后将 class active 添加到单击的项目,然后 .dropdown-toggle:not('.active'(.hide((
在您的自定义中.js您可以更改以下行:
// On click sub menu
$('.dropdown-toggle').click(function(){
$(this).next('.dropdown').toggle();
});
$(document).click(function(e) {
var target = e.target;
if (!$(target).is('.dropdown-toggle') && !$(target).parents().is('.dropdown-toggle')) {
$('.dropdown').hide();
}
});
跟:
//
// delegate the click event handler
//
$(document).on('click', '.dropdown-toggle', function(e) {
//
// is current submenu visible?
//
var isVisible = $(this).next('.dropdown').is(':visible');
//
// hide all submenu, not current
//
$(this).siblings('.dropdown-toggle').next('.dropdown').hide();
//
// toggle the visibility of current menu: visible <--> invisible
//
$(this).next('.dropdown').toggle(!isVisible);
});