Hide a DIV when it loses focus/blur

后端 未结 11 585
长情又很酷
长情又很酷 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 09:00

    On triggering mouseup() event, we can check the click is inside the div or a descendant and take action accordingly.

    $(document).mouseup(function (e) {
        var divContent= $(".className");
        if(!divContent.is(e.target) && divContent.has(e.target).length === 0) {
            $(".className").hide();
        }
    });
    
    0 讨论(0)
  • 2021-02-05 09:04
    $(document).mouseup(function (e)
    {
        var container = $("YOUR CONTAINER SELECTOR");
    
       if (!container.is(e.target)&& container.has(e.target).length === 0) 
       {
          container.hide();
       }
    });
    
    0 讨论(0)
  • 2021-02-05 09:04

    You can bind a function on click of body and check if its the current div using e.target (e is the event)

    $(document).ready(function () {
      $("body").click(function(e) {     
        if($(e.target).attr('id') === "div-id") {
            $("#div-id").show();
        }
        else {
            $("#div-id").hide();
        }
      });
    });
    
    0 讨论(0)
  • 2021-02-05 09:06

    I personally haven't tried blur on divs, only on inputs etc. If blur eventhandler works, it's perfect and use it. If it doesn't, you could check this out: jQuery animate when <div> loses focus

    0 讨论(0)
  • 2021-02-05 09:11

    For the hide the div when clicking any where on page except the selecteddiv

    $(document).not("#selecteddiv").click(function() {
            $('#selecteddiv').hide();
        });
    

    if you want to hide the div with lost focus or blur with animation then also

    $("#selecteddiv").focusout(function() {
            $('#selecteddiv').hide();
        });
    

    with animation

    $("#selecteddiv").focusout(function() {
        $('#selecteddiv').animate({
            display:"none"
        });
    });
    

    May this will help you

    0 讨论(0)
提交回复
热议问题