jquery需要替代focusout()
鉴于样本标记:
如何通过jQuery确定div
失去焦点?
我可以使用focusout()
但这不是我需要的。 通过焦点输出,它将作为一个选项卡从输入到输入触发,因为它实际上正在检测(通过事件冒泡)输入正在失去焦点。
说出要求的另一种方式:我需要知道焦点何时移动到div的外部。
我之前问过类似的问题:
jquery focusin()并防止冒泡
但这与弹出式UI有关,可以通过在其后面插入一个空白DIV并在其上放置一个click / focus事件作为触发器来绕过它,但这对于这种情况不起作用。
我的下一个想法是在调用focusout时测试focusin:
$(".myobject").focusout(function(element) { if(!($(this).focusin())){ console.log('doYourThing ' + $(this)); } });
唉,这不起作用(我猜是因为它在焦点事件期间评估焦点,因此,它还没有检测到焦点。
这个问题的任何聪明的解决方案? 我可能错过了一个原生的jQuery事件,它正是我正在寻找的东西吗?
更新:
实际上,简化的问题:
我需要相当于$('div').blur()
但这实际上可以在div上工作(因为模糊不能从div触发)
好吧,可能有用的是将“焦点”处理程序绑定到所有内容,并且当你在其他地方获得“焦点”事件时,你就知道你何时不在
。
$('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; } }; });
采取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("Lost Focus!"); });
jsfiddle演示
另一个要看的插件是Ben Alman的Outside Events插件 。 它允许您检测何时在特定元素及其子元素之外的任何事件上触发以下任何事件: clickoutside, dblclickoutside, focusoutside, bluroutside, mousemoveoutside, mousedownoutside, mouseupoutside, mouseoveroutside, mouseoutoutside, keydownoutside, keypressoutside, keyupoutside, changeoutside, selectoutside, submitoutside
。