Jquery div to open/close hidden div properly

This question already has an answer here:

  • How do I detect a click outside an element? 76 answers

  • $(document).click(function (eventObj) {
        if (eventObj.target.id != "help-icon") {
            $("#help-menu").hide();
        } else {
            $("#help-menu").toggle();
        }
    });
    

    编辑:如果你想单击出现的div而不会再隐藏它:

    $(document).click(function(eventObj)
    {
        if (eventObj.target.id == "help-icon") {
            $("#help-menu").toggle();
        } else if($(eventObj.target).hasClass("help-dropdown"))  {
            $("#help-menu").show();
        } else {
            $("#help-menu").hide();
        }
    
    
    });
    

    In my test, the mouseup function fires before the click function. The mouseup function checks for the target of the event. When you click on the button, the target of the mouseup event is the button, so the mouseup function hides the div, then the click function fires and toggles the div back to visible.

    What I would do instead is just check the target of the event in mouseup and skip the click event:

    $(document).mouseup(function (e)
        {
            var hlpcont = $("#help-menu");
            var hlpIcon = $("#help-icon");
            if(hlpIcon.is(e.target)){
                hlpcont.toggle();
            }else
                {
                  hlpcont.hide(); 
                }
    
        });
    
    链接地址: http://www.djcxy.com/p/14722.html

    上一篇: 如何通过点击任何地方关闭javascript下拉菜单?

    下一篇: jquery div正确地打开/关闭隐藏的div