我目前正在使用以下jQuery脚本:http://davidwalsh.name/twitter-dropdown-jquery - 我遇到了一个具体问题。以下jQuery脚本类似于Twitter的登录,它切换div。但是,使用此脚本,我无法切换出div(通过单击开箱或分配用于打开它的文本)。我已经附加了代码,我很确定代码的结尾处理这个问题,我只是不确定如何更改它以便它不会破坏脚本。我希望用户能够只需单击打开它的链接,在完成后将其切换为关闭状态。如果有人能提供帮助那就太棒了!
我似乎无法发布整个jQuery脚本,但我提供了一个指向代码可供查看的位置的链接。
答案 0 :(得分:2)
您只需更改一小段代码:
/* function to show menu when clicked */
dropdown.bind('click',function(e) {
if(e) e.stopPropagation();
if(e) e.preventDefault();
if(menu.is(':visible'){
hideMenu();
} else {
showMenu();
}
});
让我知道它是否有效,因为它完全未经测试。
编辑:查看@ ihumanable的答案,他在询问任何反馈之前都会真正测试代码。 :)
答案 1 :(得分:2)
在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();
}
}
});
});
有些事情一开始并不明显,当你点击一个元素时会引发焦点事件并触发点击事件,因为焦点会显示菜单,你不能只检查那里的状态,因为它会显示和快速隐藏菜单。这就是为什么我在隐藏之前添加了click事件检查的focusFired标志。