jQuery需要替代focusout() [英] jquery need alternative to focusout()

查看:107
本文介绍了jQuery需要替代focusout()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出示例标记:

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

一个人如何通过jQuery确定div失去了焦点?

How can one, via jQuery, determine that div has lost focus?

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

I can use focusout() but that's not quite what I need. With focusout, it will get triggered as one tabs from input to input, as it's actually detecting (via event bubbling) that the input is losing focus.

表达要求的另一种方式:我需要知道焦点何时移到div的外侧.

Another way to word the requirement: I need to know when focus has moved OUTSIDE of the div.

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

I asked a similar question before:

jquery focusin()并防止冒泡

但这与弹出式UI有关,可以通过在其后插入空白DIV并在其上放置click/focus事件作为触发器来解决此问题,但是在这种情况下将不起作用.

But that was related to a pop-up UI and one can get around that by inserting a blank DIV behind it and putting a click/focus event on that as a trigger but that's won't work for this situation.

我的下一个想法是在调用聚焦输出时测试聚焦输入:

The next thought I had was to test for focusin when calling focusout:

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

A,这行不通(我猜是因为它在焦点事件期间正在评估focusin,因此还没有检测到聚焦.

Alas, that doesn't work (I'm guessing due to the fact that it's evaluating focusin during the focusout event and, as such, it hasn't detected focusin yet.

对这个问题有什么聪明的解决方案吗?我可能会错过符合我所要查找功能的本地jQuery事件吗?

Any clever solutions to this problem? Am I maybe missing a native jQuery event that does exactly what I'm looking for?

更新:

实际上,简化的问题:

我需要等价于$('div').blur()的方法,但这实际上可以在div上工作(因为无法从div触发模糊)

I need the equivalent of $('div').blur() but that would actually work on a div (since blur can't be triggered from a div)

推荐答案

好吧,可行的方法是将焦点"处理程序绑定到所有内容,并且您知道当您不在<div>中时另一个焦点"事件.

Well, what might work would be to bind a "focus" handler to everything, and you know when you're not in the <div> when you get a "focus" event elsewhere.

$('body').live('focus', (function() {
  var inDiv = false;
  return function(e) {
    if ($(this).closest('#theDiv').length)
      inDiv = true;
    else {
      if (inDiv)
        alert("just lost focus!");
      inDiv = false;
    }
  };
 });

这篇关于jQuery需要替代focusout()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆