简体   繁体   English

window.onblur无法正常工作

[英]window.onblur not working

I can't seem to get window.onblur to work properly. 我似乎无法使window.onblur正常工作。

window.onblur = console.log('blur');

When the listener is applied to the window, it just runs when the page is loaded, but not when the window looses focus. 将侦听器应用于窗口时,它仅在加载页面时运行,而不是在窗口失去焦点时运行。

Ryudice has told you what to do, but didn't explain why it didn't work your way. Ryudice告诉了您该怎么做,但没有说明为什么它没有按照您的方式工作。 Understanding the mechanics of it will help you work out how to proceed further. 了解它的机制将帮助您确定如何进一步进行。

The reason is that your original code is running the console.log('blur') command immediately, and using the return value of that call as the window onblur event. 原因是您的原始代码正在立即运行 console.log('blur')命令,并将该调用的返回值用作窗口onblur事件。

The return value of console.log() varies between browsers, but for the sake of argument, lets say it returns a boolean true value. console.log()的返回值在不同的浏览器中有所不同,但是出于参数的考虑,可以说它返回布尔值true This means that your original code is the equivalent of writing this: 这意味着您的原始代码等同于编写以下代码:

window.onblur = true;

Which clearly isn't going to work as you expect. 显然,这将无法按预期工作。

What you need is for window.onblur to be set to a function that will be called each time the onblur event is triggered. 您需要将window.onblur设置为每次触发onblur事件时都会调用的函数。 This is achieved by wrapping the code in a function() {} , as per Ryudice's answer. 根据Ryudice的回答,可以通过将代码包装在function() {}中来实现。

You can also achieve it in simple cases by not supplying the brackets on the function name you want to call. 在简单情况下,您也可以通过不提供要调用的函数名称的方括号来实现此目的。 But this method only works if you don't have any arguments you want to pass to the function, so wouldn't be suited to your console.log example. 但是,仅当您没有要传递给函数的参数时,此方法才有效,因此不适合您的console.log示例。

Hope that helps. 希望能有所帮助。 If you're still puzzled, there's lots of resources on the web. 如果您仍然感到困惑,那么网络上有很多资源。 Try googling for phrases like "javascript passing functions as arguments", and see what comes up. 尝试使用谷歌搜索短语,例如“将JavaScript作为参数传递函数”,然后看看会发生什么。

window.onblur = function() { console.log('blur'); }
window.onblur = () => console.log( "blur" );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM