简体   繁体   中英

Hide a DIV when it loses focus/blur

我有一个显示DIV的JavaScript(将其显示css属性从'none'设置为'normal'。有没有办法让它集中注意力,以便当我点击页面上的其他地方时,DIV失去焦点,它display属性设置为none(基本上隐藏它)。我正在使用JavaScript和jQuery

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

The examples already given unfortunately do not work if you have an iframe on your site and then click inside the iframe. Attaching the event to the document will only attach it to same document that your element is in.

You could also attach it to any iframes you're using, but most browsers won't let you do this if the iframe has loaded content from another domain.

The best way to do this is to copy what's done in the jQuery UI menubar plugin.

<div id="menu">Click here to show the menu
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li><a href="#">Item 3</a></li>
    </ul>
</div>

var timeKeeper;

$('#menu').click(function()
{
    $('#menu ul').show();
});

$('#menu ul').click(function()
{
    clearTimeout(timeKeeper);                  
});

$('#menu').focusout(function()
{
    timeKeeper = setTimeout(function() {$('#menu ul').hide()}, 150);
});

$('#menu').attr('tabIndex', -1);
$('#menu ul').hide();

What it does is give the menu a tab index, so that it can be considered to have focus. Now that you've done that you can use the focusout event handler on the menu. This will fire whenever it has been considered to lose focus. Unfortunately, clicking some child elements will trigger the focusout event (example clicking links) so we need to disable hiding the menu if any child elements have been clicked.

Because the focusout event gets called before the click event of any children, the way to achieve this is by setting a small timeout before hiding the element, and then a click on any child elements should clear this timeout, meaning the menu doesn't get hidden.

Here is my working jsfiddle example

$(document).mouseup(function (e)
{
    var container = $("YOUR CONTAINER SELECTOR");

   if (!container.is(e.target)&& container.has(e.target).length === 0) 
   {
      container.hide();
   }
});

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:

<div class="popup">
  <input type="text" name="t1">
  <input type="text" name="t2">
</div>

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.

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();
    }
  });
});

I was also looking for this and here I found the solution https://api.jquery.com/mouseleave/ . This may be useful for future readers.

The mouseleave event differs from mouseout in the way it handles event bubbling. If mouseout were used in this example, then when the mouse pointer moved out of the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseleave event, on the other hand, only triggers its handler when the mouse leaves the element it is bound to, not a descendant.

$('.menu > li').click(function() {
    $(this).children('ul').stop().slideDown('fast',function()
    {
        $(document).one('click',function()
        {
            $('.menu > li').children('ul').stop().slideUp('fast');
        });
    });

});

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();
    }
});

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

Showing is easy

$('somewhere').click(function {$('#foo').show();})

For hiding

How do I hide a div when it loses its focus?

With jQuery you can hide elements with hide() , ex: $("#foo").hide()

Hide element in event listener:

$("#foo").blur(function() {
    $("#foo").hide();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM