如何为 window 提供 onblur 监听器
How to give onblur listenter to window
问题是,
单击浏览器时,背景颜色必须为 "white",并且
当您在浏览器之外的某个地方单击时,它必须变成 "lightgray"。
我想我可以通过为 window 对象提供 onblur 侦听器和 onfocus 侦听器来实现这一点。
但没有成功。
我试过两种方法....有谁知道我遇到的问题吗?
谢谢
更改此行
document.style.backgroundColor = 'lightgrey';
到
document.body.style.backgroundColor = "lightgrey";
window.addEventListener('blur', function() {
document.body.style.backgroundColor = "lightgrey";
});
为了设置文档(即 html
元素的)样式,您必须使用 document.documentElement.style
,而不是 document.style
。
为了将来自己检测此类错误,您应该始终检查浏览器开发人员控制台 (F12) 中的控制台输出是否存在语法错误或其他有用的消息,
// set the initial value:
document.documentElement.style.backgroundColor = document.hasFocus() ? 'yellow' : 'lightgrey';
window.addEventListener('focus', function() {
document.documentElement.style.backgroundColor = 'yellow';
});
window.addEventListener('blur', function() {
document.documentElement.style.backgroundColor = 'lightgrey';
});
问题是, 单击浏览器时,背景颜色必须为 "white",并且 当您在浏览器之外的某个地方单击时,它必须变成 "lightgray"。 我想我可以通过为 window 对象提供 onblur 侦听器和 onfocus 侦听器来实现这一点。 但没有成功。 我试过两种方法....有谁知道我遇到的问题吗? 谢谢
更改此行
document.style.backgroundColor = 'lightgrey';
到
document.body.style.backgroundColor = "lightgrey";
window.addEventListener('blur', function() {
document.body.style.backgroundColor = "lightgrey";
});
为了设置文档(即 html
元素的)样式,您必须使用 document.documentElement.style
,而不是 document.style
。
为了将来自己检测此类错误,您应该始终检查浏览器开发人员控制台 (F12) 中的控制台输出是否存在语法错误或其他有用的消息,
// set the initial value:
document.documentElement.style.backgroundColor = document.hasFocus() ? 'yellow' : 'lightgrey';
window.addEventListener('focus', function() {
document.documentElement.style.backgroundColor = 'yellow';
});
window.addEventListener('blur', function() {
document.documentElement.style.backgroundColor = 'lightgrey';
});