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