1

该脚本通过在单击时切换 .open 和 .close 类来运行我的下拉菜单。当用户在菜单外单击时,如何关闭此下拉菜单?

<script>
    $(document).ready(function(){
        $("li").addClass("closed");
        $("li.sel").on("click",function(e){
            e.preventDefault()
            });
        $("#navi1 li").click(function(){
            $("#navi1 li").toggleClass("open");
            });
        });
</script>
4

3 回答 3

1

你有没有尝试过

$("yourNavMenu").blur(function(){
   // Add your close class
});
于 2013-06-27T18:46:01.673 回答
0

Here is how I did it. Essentially, you need to call a function on any click event, and, for every menu, if the event does not occur within that menu or one of the menu's child elements, then the menu's close function is called. Of course, your close function will edit the class attribute instead of using the jQuery fade functions. As you can see, I have several menus called "subscribe", "about me", "about this website", etc. I hope this helps.

$(document).ready(function(){

    // menu hide/show logic
    var TOGGLE_SPEED = 100;

    var subscribe_menu = $("#subscribe-container");
    var about_me = $("#about-me-container");
    var about_this_website = $("#about-this-website-container");
    var filter_menu = $("#filter-menu-container");
    var img_menu = $("#img-menu-container");

    var menuList = [subscribe_menu, about_me, about_this_website, filter_menu, img_menu];

    function hideMenu(menu){
        menu.fadeOut(TOGGLE_SPEED);
    }

    function showMenu(menu){
        menu.fadeIn(TOGGLE_SPEED);
    }

    function toggleMenu(menu){
        menu.fadeToggle(TOGGLE_SPEED);
    }

    function hideOthers(e){
         for (var i in menuList) {
            var menu = menuList[i];
            // check to see if the event target is the menu
            // or one of its children
            if (!menu.is(e.target) && menu.has(e.target).length === 0) { hideMenu(menu); }
        };
    }

    function clickHandler(menu){
        var e = $.Event("click");
        e.target = menu;
        hideOthers(e);
        toggleMenu(menu);
    }

    $(document).click(function(e){
        hideOthers(e);
    });

    $("#subscribe-tab").click(function(){
        clickHandler(subscribe_menu);
        return false;
    });

    $("#about-me-tab").click(function(){
        clickHandler(about_me);
        return false;
    });

    $("#about-this-website-tab").click(function(){
        clickHandler(about_this_website);
        return false;
    });

    $("#filter-tab").click(function(){
        clickHandler(filter_menu);
        return false;
    });

    $("#img-menu-button").click(function(){
        clickHandler(img_menu);
        return false;
    });

});
于 2013-06-27T18:48:48.330 回答
0

像这样的东西应该工作:

$('*').not('#navi li').click(function(){
    $('#navi li').hide();
});
于 2013-06-27T18:46:24.843 回答