且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检测div何时失去焦点?

更新时间:2022-06-24 09:56:53

如果您希望将输入对的输入和退出视为组合成单个控件,则需要查看元素获得焦点位于相同的编辑器中。你可以这样做,使用 setTimeout 为0,将检查延迟一个周期(等待所有当前任务完成)。

If you wish to treat entry and exit of the pairs of inputs as if they were combined into a single control, you need to see if the element gaining focus is in the same editor. You can do this be delaying the check by one cycle using a setTimeout of 0 (which waits until all current tasks have completed).

$('div.editor input').focusout(function () {
    var $editor = $(this).closest('.editor');
    // wait for the new element to be focused
    setTimeout(function () {
        // See if the new focused element is in the editor
        if ($.contains($editor[0], document.activeElement)) {
            $editor.addClass("focused").removeClass("loading");
        }
        else
        {
            $editor.removeClass("focused").addClass("loading");
        }
    }, 1);
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/8s8ayv52/18/

JSFiddle: http://jsfiddle.net/TrueBlueAussie/8s8ayv52/18/

完成拼图(获得初始绿色状态) )你还需要捕获 focusin 事件,看看它是否来自来自相同的编辑器(保存以前的焦点元素)全球等)。

To complete the puzzle (get your initial green state) you will also need to also catch the focusin event and see if it is coming from the same editor or not (save the previous focused element in a global etc).

附注:我最近不得不编写一个jQuery插件,为元素组完成所有这些操作。它生成自定义 groupfocus groupblur 事件,以使其余代码更易于使用。

Side note: I recently had to write a jQuery plugin that did all this for groups of elements. It generates custom groupfocus and groupblur events to make the rest of the code easier to work with.

更新1: http://jsfiddle.net/ TrueBlueAussie / 0y2dvxpf / 4 /

Update 1: http://jsfiddle.net/TrueBlueAussie/0y2dvxpf/4/

根据您的新示例,您可以反复捕捉 focusin 而不会造成任何损害,所以追踪以前的焦点是没有必要的。使用我之前的setTimeout示例解决了在div之外单击时遇到的问题。

Based on your new example, you can catch the focusin repeatedly without damage, so tracking the previous focus is not necessary after all. Using my previous setTimeout example resolves the problem you have with clicking outside the divs.

$('div.editor input').focusin(function(){
    var $editor = $(this).closest('.editor');
    $editor.addClass("focused").removeClass("loading");

}).focusout(function () {
    var $editor = $(this).closest('.editor');
    // wait for the new element to be focused
    setTimeout(function () {
        // See if the new focused element is in the editor
        if (!$.contains($editor[0], document.activeElement)) {
            $editor.removeClass("focused").each(loadData);
        }
    }, 0);
});