如何触发 (window).focus 页面加载? [英] How to trigger (window).focus on page load?
问题描述
加载页面时,焦点/模糊状态未激活.例如,当切换到另一个标签 blur
显示时,并在切换回页面时 focus
激活 - 但在页面首次加载时没有任何状态被激活,为什么?这是预期的行为还是我搞砸了什么?
When the page is loaded the focus/blur state isn't activated. When switching to for example another tab blur
show, and upon switching back to the page focus
activates – but at first load of the page none of the states are activated, why? Is this expected behavior or have I messed something up?
$(function(){
$(window).focus(function() {
document.title="focus";
});
$(window).blur(function() {
document.title="blur";
});
});
更新似乎添加 }).focus();
正如 Rory 在评论中所建议的那样不再由于浏览器的变化而不再有任何区别 - 所以我仍在寻找一种检测页面加载焦点的方法.
Update
Seems like Adding }).focus();
as suggested by Rory in the comments doesn't make any difference anymore due to changes in browsers – so I'm still looking for a way to detect focus on page load.
更新 2我添加了一个 onload 来充当假装焦点",到目前为止这是我设法想出的最好的.不知道这是否是一个合理的解决方案,所以如果您有更好的解决方案,我很乐意参与其中.
Update 2 I've added an onload to act as a "pretend focus", so far this is the best I've managed to come up with. Don't know if this a reasonable solution, so if you've got a better one I'd love to take part of it.
window.onload = function(){
document.title="focus";
};
window.onblur = function() {
document.title="blur";
};
window.onfocus = function() {
document.title="focus";
};
推荐答案
https://jsfiddle.净/lorenzo_f/362f7ot4/10/
if(document.hasFocus()) {
$( "body" ).text("Windows got focus");
} else {
$( "body" ).text("Windows lost focus");
}
$( window ).on("focus", function() {
$( "body" ).text("Windows got focus");
});
$( window ).on("blur", function() {
$( "body" ).text("Windows lost focus");
});
<!DOCTYPE html>
<html lang="it">
<head>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
这篇关于如何触发 (window).focus 页面加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!