如何将事件绑定到tab Off元素

How to bind an event to Tabbing Off an element?

本文关键字:tab Off 元素 绑定 事件      更新时间:2023-09-26

我使用下面的下拉菜单:

/* 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("点击",函数(e) {

问题是,下拉菜单打开点击或当你的标签到它。但它只在点击时关闭,而不是在你退出时关闭。

我如何绑定一个事件来表示"tab out",失去焦点,所以下拉菜单关闭?

谢谢

可以在按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
  } 
});

希望这对你有帮助。欢呼声

尝试blur事件,该事件将在控件失去焦点时触发(即,当用户单击控件外部或使用键盘制表符到下一个控件时)。

在现有的focus绑定之后添加如下内容:

dropdown.bind('blur',function() {
  // whatever tests you want
  hideMenu();
});

(这样你就不需要当前用来隐藏菜单的单独的click绑定了)

注:您也可以考虑focusout,它与blur类似,只是它会起泡。

似乎你正在寻找onblur事件?