gpt4 book ai didi

javascript - 如何知道浏览器选项卡在加载 Javascript 时是否聚焦?

转载 作者:行者123 更新时间:2023-11-29 15:04:17 24 4
gpt4 key购买 nike

有个类似的问题here .但是当页面最初加载时它不起作用,因为如果用户在新选项卡中打开页面并且它没有获得焦点,blur 事件将不会触发。

那么最好的方法是什么?

目前,我的临时解决方案是假设选项卡在加载时是模糊的,并将一个函数绑定(bind)到文档的鼠标悬停事件,将其设置为聚焦。但如果用户没有将鼠标放在页面上,那将不起作用。

最佳答案

借用您链接到的代码,将默认设置为模糊:

<div id="blurDiv"></div>

<script>

var updateStatus = (function() {

// Private stuff
var el = document.getElementById('blurDiv');

// The updateStatus function
return function (evt) {
evt = evt || window.event;
var evtType = evt.type;
var state;

// Determine state
if (evtType == 'load' || evtType == 'blur' || evtType == 'focusout' ) {
state = 'blurred';
} else {
state = 'focussed';
}

// Now do something...
el.innerHTML += '<br>' + state
};
})();

window.onload = updateStatus;

if (/*@cc_on!@*/false) { // check for Internet Explorer
document.onfocusin = updateStatus;
document.onfocusout = updateStatus;
} else {
window.onfocus = updateStatus;
window.onblur = updateStatus;
}

</script>

IE 似乎触发了很多额外的事件,每次获得焦点时,首先是模糊,然后是焦点,因此点击页面中的东西会有很多虚假的模糊/焦点对。

关于javascript - 如何知道浏览器选项卡在加载 Javascript 时是否聚焦?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5481198/

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