Hide a DIV when it loses focus/blur

后端 未结 11 812
长情又很酷
长情又很酷 2021-02-05 08:34

I have a JavaScript that displays a DIV (sets its display css property from \'none\' to \'normal\'. Is there a way to give it focus as well so that when I click somewhere else o

11条回答
  •  悲哀的现实
    2021-02-05 08:52

    Regarding mouse clicks, see the other answers.

    However regarding lost focus, .focusout is not the event to attach to, but rather .focusin. Why? Consider the following popup:

    
    

    What happens on moving from t1 to t2:

    • t1 sends focusout, which bubbles up to $('.popup').focusout
    • t2 sends focusin, which bubbles up to $('.popup').focusin

    ... so you get both types of event even though the focus stayed completely inside the popup.

    The solution is to analogous to the magic trick done with .click:

    $(document).ready(function() {
        $('html').focusin(function() {
            $('.popup').hide(); 
        });
        $('.popup').focusin(function(ev) {
            ev.stopPropagation(); 
        });
    });
    

    (side note: I found the .not(...) solution not working bc. of event bubbling).

    Bonus: working fiddle click me - open the popup, then try tabbing through the inputs.

提交回复
热议问题