我正在使用以下内容进行下拉列表:
/* 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 show menu when clicked */
dropdown.bind('click',function(e) {
if(e) e.stopPropagation();
if(e) e.preventDefault();
showMenu();
});
/* function to show menu when someone tabs to the box */
dropdown.bind('focus',function() {
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();
}
}
});
注意:
$(document.body).bind('click',function(e){
问题是,下拉菜单会在点击或选中它时打开。但它只会在点击时关闭,而不是在您退出时关闭。
如何将事件绑定为“标记”,失去焦点,以便下拉关闭?
由于
答案 0 :(得分:4)
按Tab键时,可以在外面触发一次单击。像这样:
$('#your_dropdown').bind('keydown', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) { //If it's the tab key
$("body").click(); //Force a click outside the dropdown, so it forces a close
}
});
希望这会有所帮助。干杯
答案 1 :(得分:1)
尝试blur
事件,该事件将在控件失去焦点时触发(即,当用户点击控件外部或使用键盘标签到下一个控件时)。
在您现有的focus
绑定之后输入类似的内容:
dropdown.bind('blur',function() {
// whatever tests you want
hideMenu();
});
(您不应该需要单独使用单独的点击装订来隐藏菜单。)
P.S。您可能还会考虑focusout
,它与blur
类似,只不过它会起泡。
答案 2 :(得分:0)
好像你正在寻找onblur
事件?