窗口 onload 和窗口 onfocus

发布于 2024-11-16 07:16:57 字数 281 浏览 3 评论 0原文

window.onload = function() {
window.onfocus = alert('example');
}

我遇到了这个问题,有人可以帮忙吗? 我是 javascript 新手,希望能正常工作,但事实并非如此:)

我想在页面完全加载并处于活动状态时提醒“示例”一词,但不想提醒“示例”一词如果页面已完全加载但未处于活动状态 (onblur)。 当用户回来时(onfocus),然后提醒“example”。

window.onload = function() {
window.onfocus = alert('example');
}

I've met this problem, anyone can help?
I'm new at javascript and made this expecting to work properly, but it does not :)

I want to alert the word "example" when the page is fully loaded and active, but don't want to alert the word "example" if the page is fully loaded but not active (onblur).
And when user comes back (onfocus) then alert "example".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

虫児飞 2024-11-23 07:16:57

您的代码立即调用alert函数,并将其返回值分配给onfocus

您需要将 onfocus 设置为调用 alert 的匿名函数:

window.onload = function() { 
    window.onfocus = function() { alert('example'); };
};

Your code calls the alert function immediately and assigns its return value to onfocus.

You need to set onfocus to an anonymous function that calls alert:

window.onload = function() { 
    window.onfocus = function() { alert('example'); };
};
时光匆匆的小流年 2024-11-23 07:16:57

试试这个:

var hasFocus=false;
var loaded = false;

window.onload = function() {
    if (hasFocus) alert('example');
    loaded = true;
};
window.onfocus = function() { 
    if (loaded) alert('example');
    hasFocus = true;
};
window.onblur = function() { hasFocus = false; };

Try this:

var hasFocus=false;
var loaded = false;

window.onload = function() {
    if (hasFocus) alert('example');
    loaded = true;
};
window.onfocus = function() { 
    if (loaded) alert('example');
    hasFocus = true;
};
window.onblur = function() { hasFocus = false; };
嗫嚅 2024-11-23 07:16:57
window.onload = function() { 
    window.onfocus = function() {
        alert('example'); 
    }
}
window.onload = function() { 
    window.onfocus = function() {
        alert('example'); 
    }
}
时光暖心i 2024-11-23 07:16:57

这是您需要的 JavaScript。

<html>
<head>
    <script type="text/javascript">
        window.onload = init;

        function init() { window.onfocus = whenInFocus; window.onblur = function() {window.onfocus = whenInFocus;};};
        function whenInFocus() {alert('example'); window.onfocus = null;};
    </script>

</head>
<body>
    hello
</body>
</html>

Here is the javascript that you need.

<html>
<head>
    <script type="text/javascript">
        window.onload = init;

        function init() { window.onfocus = whenInFocus; window.onblur = function() {window.onfocus = whenInFocus;};};
        function whenInFocus() {alert('example'); window.onfocus = null;};
    </script>

</head>
<body>
    hello
</body>
</html>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文