gpt4 book ai didi

javascript - $(window).focus() 为每个焦点运行两次

转载 作者:搜寻专家 更新时间:2023-11-01 04:33:38 24 4
gpt4 key购买 nike

我不确定为什么会这样,我很想得到解释。

我使用 jquery 的 focus 方法绑定(bind)到窗口焦点事件。这是一个工作示例(复制粘贴到 html 文件并在浏览器中打开。由于某种原因在 jsfiddle 或 jsbin 中不起作用)

<!DOCTYPE html>
<html>

<head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script></head>

<body>
<p1>Here:</p1>
<div id="here" >Why</div>
</body>
<script>
$(window).load(function() {
$(window).focus(function() {console.log("focus");});
$(window).blur(function() {console.log("blur");});
});
</script>
</html>

当浏览器重新获得焦点时,该函数将运行两次并且“focus”被打印到控制台两次。知道为什么会这样吗?

顺便说一句,最终目标是在用户将浏览器离开到应用程序或另一个选项卡时停止计时器运行。

更新

在最新的(开发)版本的 chrome 上运行。我会在 firefox 上测试它,如果那里有不同,我会写下来。

更新 2有趣的事实 - 不会发生在 firefox 上。可能是 chrome 的一个错误。

最佳答案

我遇到了同样的问题。我对此的修复是使用 lodash 的 debounce() 函数 ( https://lodash.com/docs/#debounce )。这是我的修复:

var debouncedFocus = _.debounce(() => {
console.log('focussed');
}, 250, {leading: true, trailing: false});

$(window).on('focus', debouncedFocus);

关于javascript - $(window).focus() 为每个焦点运行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7953790/

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