jquery 需要 focusout() 的替代方案

标签 jquery focusout

给定示例标记:

<div>
    <input />
    <input />
    <input />
</div>

如何通过 jQuery 确定 div 失去焦点?

我可以使用 focusout() 但这并不是我所需要的。使用 focusout,它将作为从一个输入到另一个输入的一个选项卡被触发,因为它实际上检测(通过事件冒泡)输入正在失去焦点。

表达需求的另一种方式:我需要知道焦点何时移出 div。

我之前也问过类似的问题:

jquery focusin() and preventing bubbling

但这与弹出式 UI 有关,可以通过在其后面插入空白 DIV 并在其上放置单击/焦点事件作为触发器来解决此问题,但这不适用于这种情况。

我的下一个想法是在调用 focusout 时测试 focusin:

    $(".myobject").focusout(function(element) {
    if(!($(this).focusin())){
        console.log('doYourThing ' + $(this));
    }
});

唉,这不起作用(我猜测是因为它在 focusout 事件期间评估 focusin,因此它尚未检测到 focusin。

有什么巧妙的方法可以解决这个问题吗?我是否可能缺少一个 native jQuery 事件,而该事件正是我正在寻找的?

更新:

实际上,简化的问题:

我需要相当于 $('div').blur() 但这实际上可以在 div 上工作(因为不能从 div 触发模糊)

最佳答案

采用 Pointy 的答案并进一步探讨。

创建一个(简单的)focuslost 事件插件

(function($) {
    // will store the last focus chain
    var currentFocusChain = $();
    // stores a reference to any DOM objects we want to watch focus for
    var focusWatch = [];

    function checkFocus() {
        var newFocusChain = $(":focus").parents().andSelf();
        // elements in the old focus chain that aren't in the new focus chain...
        var lostFocus = currentFocusChain.not(newFocusChain.get());
        lostFocus.each(function() {
            if ($.inArray(this, focusWatch) != -1) {
                $(this).trigger('focuslost');
            }
        });
        currentFocusChain = newFocusChain;
    }
    // bind to the focus/blur event on all elements:
    $("*").live('focus blur', function(e) { 
        // wait until the next free loop to process focus change
        // when 'blur' is fired, focus will be unset
        setTimeout(checkFocus, 0);
    });

    $.fn.focuslost = function(fn) {
        return this.each(function() {
            // tell the live handler we are watching this event
            if ($.inArray(this, focusWatch) == -1) focusWatch.push(this);
            $(this).bind('focuslost', fn);
        });
    };
})(jQuery);

使用示例

$("div").focuslost(function() {
  $(this).append("<div>Lost Focus!</div>");
});

jsfiddle demo

关于jquery 需要 focusout() 的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3088738/

相关文章:

jquery - fork jQuery 以将其内置组件之一 fork 为插件?

javascript - Twitter 的 Bootstrap 2.x 弹出框选择器和关闭问题

javascript - 区分内页和外页的焦点丢失?

javascript - 当外部点击 IOS 设备时,使 Slicknav 菜单关闭

javascript - 模糊事件.relatedTarget 返回 null

jQuery 从 iframe 代码获取 YouTube 视频 src

jquery - Div 和 Jquery Slider 的堆叠问题

jquery - 使用 Angularjs 动态生成之前/之后的 CSS 伪内容