Javascript body OnClick

后端 未结 3 1156
攒了一身酷
攒了一身酷 2021-02-20 13:33

I\'m in the process of learning Javascript and I\'m trying to create a simple dropdown menu. An example of my desired functionality can be seen on the google homepage in the top

3条回答
  •  离开以前
    2021-02-20 14:03

    You can capture a click anywhere if you put onclick on the body. Because of the javascript event propagation model, if you click anywhere on any element and you don't stop the event from propagating, it will reach body and hide the menus.

    So basically this means that you want to capture body onclick and make it to hide the menus so when you click on any area of the page, it will close the menus.

    But this hides a bit of unwanted behaviour - when you click on the button to show the menu, the menu will display and quickly after that hide (when the event reaches body). To prevent this, you will want to stop the event from propagating when you click on the button which shows the menu (you can see how this works in the code I posted below). The code shows where you need to touch to make it work nicely.

    // this function stops event e or window.event if e is not present from 
    // propagating to other elements.
    function stop_event(e) {
       if(!e) {
          e = window.event;
       }
       if (e.stopPropagation) e.stopPropagation();
       e.cancelBubble = true;
       if (e.preventDefault) e.preventDefault();
       e.returnValue = false;
       return false;
    }
    
    // now you just hide all the menus in your hideMenus
    function hideMenus()
    {
        //pseudocode!
        for all visible menus - hide // or if you want you can hide all menus, 
                                     // the hidden will remain hidden
    }
    

    Now the important part.

    function menu(id) {     
        // your stuff here
        stop_event(); // this will stop the event going down to the body 
                      // and hiding it after showing it
                      // this means it will not flicker like: show-hide
    }  
    

    And finally on your whole UL element:

    //partly pesudocode
    ul.onclick = function() { stop_event(); }
    

    To explain again what this does:

    1st. You hook your hideMenu function to body.onclick. This means that it will always hide the menus if we don't stop the event.

    2nd. When you click the menu button, you show the menu and then we stop the event from going to the body. This way, the body.onclick will not fire and it will not hide the menu right after we opened it.

    3rd. The ul.onclick means that the menu will not hide itself when we click on it (though if you want the menu to hide when you click the menu itself, you can remove this part).

提交回复
热议问题