gpt4 book ai didi

javascript - 从 onBlur 事件中获取新聚焦的元素(如果有的话)。

转载 作者:可可西里 更新时间:2023-11-01 02:52:24 25 4
gpt4 key购买 nike

我需要在执行 onBlur 处理程序时获取新聚焦的元素(如果有的话)。

我该怎么做?

我能想到一些糟糕的解决方案,但没有一个不涉及 setTimeout。

最佳答案

引用它:

document.activeElement

不幸的是,当 blur 事件发生时,新元素没有聚焦,所以这将报告 body。所以你将不得不用标志和焦点事件来破解它,或者使用 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);
}

关于javascript - 从 onBlur 事件中获取新聚焦的元素(如果有的话)。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11592966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com