在JsFiddle中玩了一段时间后,我想出了一些代码,它可以做到你想做的事情,我试着尽可能地改变现有的代码。
$(document).ready(function() {
/* for keeping track of what's "open" */
var activeClass = 'dropdown-active',
focusFired = false,
showingDropdown, showingMenu, showingParent;
/* hides the current menu */
var hideMenu = function() {
if (showingDropdown) {
showingDropdown.removeClass(activeClass);
showingDropdown = null;
showingMenu.hide();
}
};
/* recurse through dropdown menus */
$('.dropdown').each(function() { /* track elements: menu, parent */
var dropdown = $(this);
var menu = dropdown.next('div.dropdown-menu'),
parent = dropdown.parent(); /* function that shows THIS menu */
var showMenu = function() {
hideMenu();
showingDropdown = dropdown.addClass('dropdown-active');
showingMenu = menu.show();
showingParent = parent;
};
/* function to toggle menu when clicked */
dropdown.bind('click', function(e) {
console.log('Click fired');
if (e) e.stopPropagation();
if (e) e.preventDefault();
if(showingDropdown == dropdown && !focusFired) {
hideMenu();
} else {
showMenu();
}
focusFired = false;
});
/* function to show menu when someone tabs to the box */
dropdown.bind('focus', function() {
focusFired = true;
showMenu();
});
});
/* hide when clicked outside */
$(document.body).bind('click', function(e) {
if (showingParent) {
var parentElement = showingParent[0];
if (!$.contains(parentElement, e.target) || !parentElement == e.target) {
hideMenu();
}
}
});
});
有一些事情是在第一个非显而易见的,当你点击进入某个元素的焦点事件触发和点击事件触发,因为焦点显示菜单中,你不能只检查状态,因为有它会显示并快速隐藏菜单。这就是为什么我添加了隐藏之前单击事件检查的focusFired标志。
那么...你的代码在哪里? – DarthJDG 2011-05-19 13:56:16
该代码是在这里找到完全相同的代码:http://davidwalsh.name/twitter-dropdown-jquery - 我试图发布整个jQuery脚本,但它不会让我。 – BrianJ 2011-05-19 14:14:49
如果它在那里工作,它一定有一些区别,但它不适合你。 :)你可以尝试在jsfiddle.net上设置它? – DarthJDG 2011-05-19 14:16:17