在执行onBlur处理程序时,我需要获得新聚焦的元素(如果有的话)。
我该怎么做?
我能想出一些糟糕的解决方案,但没有一个不涉及setTimeout。
引用:
document.activeElement
不幸的是,当模糊事件发生时,新元素没有被聚焦,所以这将报告正文。所以你必须用标志和焦点事件来破解它,或者使用setTimeout。
$("input").blur(function() {
setTimeout(function() {
console.log(document.activeElement);
}, 1);
});
工作良好。
没有setTimeout,你可以使用这个:
http://jsfiddle.net/RKtdm/
(function() {
var blurred = false,
testIs = $([document.body, document, document.documentElement]);
//Don't customize this, especially "focusIN" should NOT be changed to "focus"
$(document).on("focusin", function() {
if (blurred) {
var elem = document.activeElement;
blurred = false;
if (!$(elem).is(testIs)) {
doSomethingWith(elem); //If we reached here, then we have what you need.
}
}
});
//This is customizable to an extent, set your selectors up here and set blurred = true in the function
$("input").blur(function() {
blurred = true;
});
})();
//Your custom handler
function doSomethingWith(elem) {
console.log(elem);
}
为什么不使用focusout事件?https://developer.mozilla.org/en-US/docs/Web/Events/focusout
relatedTarget属性将为您提供接收焦点的元素。