开发者

window onload and window onfocus

开发者 https://www.devze.com 2023-03-14 10:10 出处:网络
window.onload = function() { window.onfocus = alert(\'example\'); } I\'ve met this problem, anyone can help?
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开发者_StackOverflow 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".


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'); };
};


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; };


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


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消