1

我在一个 div 中有两个输入框,我想将该 div 隐藏在输入的 focusOut 上,但前提是它们都没有焦点。

这是一个常见的 Firefox 问题(有人称其为遵守标准),但文档正文窃取了两者之间的焦点。

HTML


<div id="baz">
   <input type="text" id="foo" name="foo" />
   <input type="text" id="bar" name="bar" />
</div>

jQuery


// jQuery Example
jQuery(":input").focusout(function(){
   // Don't do anything if one of the input boxes has focus
   if( jQuery(":input").is( jQuery(document.activeElement) ){ return; }

   // Hide the container if one of the inputs loose focus
   jQuery(this).parents("div").css("display","none");
}

虽然这是一个常见的错误,但我忘记了我过去是如何解决的。我认为这与在检查activeElement.


jsFiddle 示例

jsFiddle 更新(FF4 相同问题)

4

2 回答 2

7

演示

jQuery(":input").focusout(function(){
    var elem = jQuery(this).parent("div");
    window.setTimeout(function(){
            // Don't do anything if one of the input boxes has focus
            if( jQuery(":input").is( jQuery(document.activeElement) )){ return; }

            // Hide the container if one of the inputs loose focus
            elem.hide();
    }, 0);
})

演示

jQuery(document).ready(function () {
    var timeoutID;

    jQuery(":input").focus(function () {
        window.clearTimeout(timeoutID);
    }).focusout(function () {
        timeoutID = window.setTimeout(function () {
            jQuery("#baz").hide();
        }, 0);
    });
});
于 2011-05-27T22:19:03.363 回答
0

我认为 amit_g 的解决方案几乎就在那里。我依稀记得我已经通过两种方式解决了这个问题:

  1. 将输入与activeElement(上面显示的方法)进行比较
  2. 为相应事件设置/清除元素上的“焦点”类

我认为这两种方法都需要 using setTimeout,因为 Firefox 有一个延迟触发器,我们需要强制执行。虽然我听说 FF 在这里遵守标准,但我个人认为该标准需要修改。


因此,除了添加定时函数调用之外,如果其他“可接受”元素获得焦点,还需要清除它。以下不是生产代码,但它确实表明它确实可以作为示例:

示例解决方案

示例解决方案(更好) - 设置$debugfalse

示例解决方案(本地化块) - 消除了调试混乱

于 2011-05-28T16:56:11.093 回答