给定示例标记:
<div>
<input />
<input />
<input />
</div>如何通过jQuery确定div已经失去了焦点?
我可以使用focusout(),但这并不是我所需要的。使用focusout,它将被触发为一个从一个输入到另一个输入的标签,因为它实际上正在检测(通过事件冒泡)输入正在失去焦点。
另一种表达要求的方式是:我需要知道焦点何时移出了div。
我之前也问过类似的问题:
jquery focusin() and preventing bubbling
但这是与弹出式UI相关的,人们可以通过在其后面插入一个空白DIV并将单击/焦点事件作为触发器来绕过它,但这在这种情况下不起作用。
我的下一个想法是在调用focusout时测试focusin:
$(".myobject").focusout(function(element) {
if(!($(this).focusin())){
console.log('doYourThing ' + $(this));
}
});遗憾的是,这不起作用(我猜是因为它在focusout事件期间评估了focusin,因此,它还没有检测到focusin。
对于这个问题有什么聪明的解决方案吗?我是不是遗漏了一个本机jQuery事件,它做的正是我想要的?
更新:
实际上,简化的问题是:
我需要$('div').blur()的等价物,但这实际上可以在div上工作(因为模糊不能从div触发)
发布于 2010-06-22 06:07:41
好的,可能可行的方法是将“焦点”处理程序绑定到所有东西上,当您在其他地方获得“<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;
}
};
});发布于 2010-06-22 06:49:48
采纳了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);示例用法
$("div").focuslost(function() {
$(this).append("<div>Lost Focus!</div>");
});jsfiddle demo
发布于 2010-06-23 02:16:32
另一个值得关注的插件是Ben Alman的Outside Events plugin。它允许您检测在特定元素及其子元素之外的任何事件上触发以下任何事件的时间:clickoutside, dblclickoutside, focusoutside, bluroutside, mousemoveoutside, mousedownoutside, mouseupoutside, mouseoveroutside, mouseoutoutside, keydownoutside, keypressoutside, keyupoutside, changeoutside, selectoutside, submitoutside。
https://stackoverflow.com/questions/3088738
复制相似问题