使用onfocus和onblur来实现窗口焦点

404 阅读1分钟
**1**
let _app = document.getElementById("app");
//得到焦点
window.onload = () => {
  _app?.focus();
};
//当前窗口得到焦点
window.onfocus = () => {
  _app?.focus();
};

//当前窗口失去焦点
window.onblur = () => {
  _app?.focus();
  console.log("游戏失去焦点。");
};

**2**
const keysToBlockWhenFramed = [32, 33, 34, 35, 36, 37, 38, 39, 40, 44];
document.addEventListener(
  "keydown",
  (info) => {
    if (window !== window.top && keysToBlockWhenFramed.indexOf(info.which) > -1) {
      info.preventDefault();
      info.stopPropagation();
    }
    const element = document.getElementById("app");
    if (element !== null) {
      element.scrollTop = 0;
    }
    window.focus();
    document.body.scrollIntoView();
  },
  true
);
document.addEventListener(
  "mousedown",
  () => {
    window.focus();
  },
  true
);
document.addEventListener(
  "touchstart",
  () => {
    window.focus();
  },
  true
);
document.addEventListener("gesturestart", (event) => {
  const _event = event || window.event;
  if (typeof _event.preventDefault !== "undefined") {
    //w3c
    _event.preventDefault();
  } else {
    _event.returnValue = false; //ie
  }
});