React 全屏監(jiān)聽(tīng)Esc鍵來(lái)達(dá)到按下修改數(shù)據(jù)

前言:前端展示越來(lái)越重要,隨著可視化圖表的功能越來(lái)越強(qiáng)大。UI展示這塊也流行。最近一個(gè)需求,全屏與退出全屏。這里附上代碼。

全屏與退出全屏

// fullscreen.js
const doc = document;
const html = doc.documentElement;

const enter =
  html.requestFullscreen ||
  html.webkitRequestFullScreen ||
  html.mozRequestFullScreen ||
  html.msRequestFullscreen;

const exit =
  doc.exitFullscreen ||
  doc.webkitCancelFullScreen ||
  doc.mozCancelFullScreen ||
  doc.msExitFullscreen;

const enterFullScreen = () => {
  enter && enter.call(html);
};

const exitFullScreen = () => {
  exit && exit.call(doc);
};

export { enterFullScreen, exitFullScreen };

使用時(shí)只需要導(dǎo)入即可
(由于我做的是一個(gè)后臺(tái)管理項(xiàng)目,這里全屏?xí)^(qū)別于別的一些項(xiàng)目。這里想說(shuō)的其實(shí)是全屏監(jiān)聽(tīng)Esc鍵來(lái)達(dá)到修改數(shù)據(jù)的目的)
使用時(shí)遇到一個(gè)問(wèn)題 :全屏狀態(tài)下按下Esc鍵,需要修改頁(yè)面數(shù)據(jù)。不然狀態(tài)不改變會(huì)出問(wèn)題。

監(jiān)聽(tīng)Esc鍵

// 這是一個(gè)demo
componentDidMount() {
  this.bindFullscreenListener ();
}

componentWillUnmount() {
  try {
    this.unBindFullscreenListener();
  } catch (e) {
    console.warn(e);
  }
}

bindFullscreenListener = () => {
  // 監(jiān)聽(tīng)退出全屏事件 --- chrome 用 esc 退出全屏并不會(huì)觸發(fā) keyup 事件
  document.addEventListener("webkitfullscreenchange", this.checkFull);
  document.addEventListener("mozfullscreenchange", this.checkFull);
  document.addEventListener("fullscreenchange", this.checkFull);
  document.addEventListener("MSFullscreenChange", this.checkFull);
};

unBindFullscreenListener = () => {
  document.removeEventListener("webkitfullscreenchange", this.checkFull);
  document.removeEventListener("mozfullscreenchange", this.checkFull);
  document.removeEventListener("fullscreenchange", this.checkFull);
  document.removeEventListener("MSFullscreenChange", this.checkFull);
};

checkFull = () => {
  if (!document.webkitIsFullScreen && !document.mozFullScreen && !document.msFullscreenElement) {
    this.setState({
      fullScreen: false,
      fullScreenBtn: "全屏",
      showBtn: true
    });
  } else {
    this.setState({
      fullScreen: true,
      fullScreenBtn: "退出全屏",
      showBtn: true
    });
  }
};

使用這個(gè)之后就可以達(dá)到按下Esc鍵去修改頁(yè)面的一些狀態(tài)的目的。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容