整个 div 和孩子的 jQuery 焦点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15369572/
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-26 14:55:16  来源:igfitidea点击:

jQuery focusout for entire div and children

jqueryjquery-focusout

提问by Helto

I have a div that I am creating dynamically via jQuery with some links/buttons in it. When this div loses focus I need to remove it. This part I can do ok.

我有一个 div,我通过 jQuery 动态创建它,其中包含一些链接/按钮。当这个 div 失去焦点时,我需要将其删除。这部分我可以做到。

However, right now I have the focusout event on the wrapper for the div and when I click on a button inside the div, the wrapper loses focus to the child and my event gets fired. Checking if the element clicked is a child of the wrapper I can do, but since the wrapper no longer has focus, my event will not fire again to remove the div.

但是,现在我在 div 的包装器上有 focusout 事件,当我单击 div 内的按钮时,包装器失去对孩子的焦点并且我的事件被触发。检查单击的元素是否是我可以执行的包装器的子元素,但由于包装器不再具有焦点,因此我的事件不会再次触发以删除 div。

I have also tried .blur, but this doesn't work any better.

我也试过 .blur,但这并没有更好的效果。

What is the best way to do this?

做这个的最好方式是什么?

回答by Isaac

$("#yourDiv").focusout(function () {
   if ($(this).has(document.activeElement).length == 0) {
       // remove div
   }
});

$(this)= the div you're focusing out of.

$(this)= 您关注的 div。

document.activeElement= the element that is currently in focus.

document.activeElement= 当前处于焦点的元素。

$(this).has(document.activeElement)is simply checking if the active element is a child of your div

$(this).has(document.activeElement)只是检查活动元素是否是您的 div 的子元素

回答by Stefan Hessler

A way of solving this with plain javascript is using the relatedTarget given in the event argument:

使用纯 javascript 解决此问题的一种方法是使用事件参数中给出的相关目标:

element.addEventListener('focusout', function(event) {
    if (element.contains(event.relatedTarget)) {
        // don't react to this
        return;
    }
    // do something
});