onfocusout / onfocusin不起作用

Bla*_*ack 2 html javascript events

我刚刚了解了onfocusoutonfocusin但是这些功能似乎不起作用。我尝试使用Firefox和Chrome。根本没有控制台消息,即使当我集中精力并松开它时也是如此。我究竟做错了什么?

window.addEventListener
(
  "onfocusout",
  function()
  {
    console.log("page lost focus");
  }
);

window.addEventListener
(
  "onfocusin",
  function()
  {
    console.log("page has focus");
  }
);
Run Code Online (Sandbox Code Playgroud)
<h1>Test</h1>
Run Code Online (Sandbox Code Playgroud)

epa*_*llo 5

使用addEventListener时,不要在事件名称上使用“ on”

function example(evt) {
    console.log(evt.type, event.target.id);  
}

window.addEventListener("focusin", example);
window.addEventListener("focusout", example);
Run Code Online (Sandbox Code Playgroud)
<input type="text" id="foo" />
<input type="text" id="bar" />
Run Code Online (Sandbox Code Playgroud)


如果你想知道的页面状态,比你需要看不同的事件:pageshowpagehide