javascript window.onblur 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10361188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
window.onblur not working
提问by Charles John Thompson III
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.
当侦听器应用于窗口时,它只会在页面加载时运行,而不会在窗口失去焦点时运行。
回答by Spudley
Ryudice has told you what to do, but didn't explain whyit didn't work your way. Understanding the mechanics of it will help you work out how to proceed further.
Ryudice 已经告诉你该怎么做,但没有解释为什么它没有按照你的方式工作。了解它的机制将帮助您确定如何进一步进行。
The reason is that your original code is runningthe 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. This means that your original code is the equivalent of writing this:
的返回值console.log()
因浏览器而异,但为了论证,假设它返回一个布尔true
值。这意味着您的原始代码相当于编写以下代码:
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. This is achieved by wrapping the code in a function() {}
, as per Ryudice's answer.
您需要的是window.onblur
设置为每次onblur
触发事件时都会调用的函数。function() {}
根据 Ryudice 的回答,这是通过将代码包装在 a 中来实现的。
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 将函数作为参数传递”之类的短语,看看会出现什么。
回答by ryudice
window.onblur = function() { console.log('blur'); }
回答by karkael
window.onblur = () => console.log( "blur" );