Javascript 失去焦点/模糊时隐藏 DIV

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5337828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:44:36  来源:igfitidea点击:

Hide a DIV when it loses focus/blur

javascriptjqueryhtml

提问by code511788465541441

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 on the page, the DIV loses focus and its display property is set to none (basically hiding it). I'm using JavaScript and jQuery

我有一个显示 DIV 的 JavaScript(将其显示 css 属性从“无”设置为“正常”。有没有办法让它获得焦点,以便当我点击页面上的其他地方时,DIV 失去焦点,它的显示属性设置为无(基本上隐藏它)。我正在使用 JavaScript 和 jQuery

回答by Harsh Chunara

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

单击页面上除 selecteddiv 之外的任何位置时隐藏 div

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

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

如果你想隐藏失去焦点的 div 或动画模糊,那么也

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

with animation

带动画

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

May this will help you

可能这会帮助你

回答by Mark

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.

不幸的是,如果您的站点上有 iframe,然后在 iframe 内单击,那么已经给出的示例将不起作用。将事件附加到文档只会将其附加到您的元素所在的同一文档。

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.

您也可以将它附加到您正在使用的任何 iframe 上,但如果 iframe 加载了来自其他域的内容,大多数浏览器将不允许您这样做。

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

最好的方法是复制在 jQuery UI 菜单栏插件中所做的事情。

Basic example HTML:

基本示例 HTML:

<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>

And the jQuery needed to make it work:

jQuery 需要让它工作:

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.

它的作用是给菜单一个标签索引,这样它就可以被认为是有焦点的。现在您已经完成了,您可以使用菜单上的 focusout 事件处理程序。每当它被认为失去焦点时就会触发。不幸的是,单击某些子元素会触发焦点事件(例如单击链接),因此如果单击了任何子元素,我们需要禁用隐藏菜单。

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.

因为 focusout 事件在任何子元素的点击事件之前被调用,实现这一点的方法是在隐藏元素之前设置一个小的超时,然后点击任何子元素应该清除这个超时,这意味着菜单没有得到隐。

Here is my working jsfiddle example

这是我的工作 jsfiddle 示例

回答by Akshay Taru

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

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

回答by naiquevin

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

您可以在单击 body 时绑定一个函数,并使用 e.target 检查它是否为当前 div(e 是事件)

$(document).ready(function () {
  $("body").click(function(e) {     
    if($(e.target).attr('id') === "div-id") {
        $("#div-id").show();
    }
    else {
        $("#div-id").hide();
    }
  });
});

回答by Torben Klein

Regarding mouse clicks, see the other answers.

关于鼠标点击,请参阅其他答案。

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

然而,关于失去焦点,.focusout不是要附加的事件,而是.focusin。为什么?考虑以下弹出窗口:

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

What happens on moving from t1 to t2:

从 t1 移动到 t2 会发生什么:

  • t1 sends focusout, which bubbles up to $('.popup').focusout
  • t2 sends focusin, which bubbles up to $('.popup').focusin
  • t1 发送focusout, 冒泡到$('.popup').focusout
  • t2 发送focusin, 冒泡到$('.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:

解决方案类似于使用以下方法完成的魔术.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).

(旁注:我发现该.not(...)解决方案在事件冒泡事件中不起作用)。

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

奖励:工作小提琴点击我- 打开弹出窗口,然后尝试浏览输入。

回答by Amit Kumar

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

我也在寻找这个,在这里我找到了解决方案https://api.jquery.com/mouseleave/。这可能对未来的读者有用。

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.

mouseleave 事件与 mouseout 处理事件冒泡的方式不同。如果在本例中使用 mouseout,那么当鼠标指针移出 Inner 元素时,将触发处理程序。这通常是不受欢迎的行为。另一方面, mouseleave 事件仅在鼠标离开它所绑定的元素时触发其处理程序,而不是后代元素。

回答by John

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

在触发 mouseup() 事件时,我们可以检查点击是否在 div 或后代内,并相应地采取行动。

$(document).mouseup(function (e) {
    var divContent= $(".className");
    if(!divContent.is(e.target) && divContent.has(e.target).length === 0) {
        $(".className").hide();
    }
});

回答by soner san

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

});

回答by daan

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

我个人没有在 div 上尝试过模糊,只在输入等上尝试过。如果模糊事件处理程序有效,那就完美了,可以使用它。如果没有,你可以看看这个: jQuery animate when <div> lost focus

回答by Santosh Linkha

Showing is easy

显示很容易

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

For hiding

为了隐藏

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

当 div 失去焦点时如何隐藏它?