前言:前端展示越來越重要帖蔓,隨著可視化圖表的功能越來越強大棚瘟。UI展示這塊也流行。最近一個需求,全屏與退出全屏俐末。這里附上代碼。
全屏與退出全屏
// 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 };
使用時只需要導入即可
(由于我做的是一個后臺管理項目奄侠,這里全屏會區(qū)別于別的一些項目卓箫。這里想說的其實是全屏監(jiān)聽Esc鍵來達到修改數(shù)據(jù)的目的)
使用時遇到一個問題 :全屏狀態(tài)下按下Esc鍵,需要修改頁面數(shù)據(jù)垄潮。不然狀態(tài)不改變會出問題烹卒。
監(jiān)聽Esc鍵
// 這是一個demo
componentDidMount() {
this.bindFullscreenListener ();
}
componentWillUnmount() {
try {
this.unBindFullscreenListener();
} catch (e) {
console.warn(e);
}
}
bindFullscreenListener = () => {
// 監(jiān)聽退出全屏事件 --- chrome 用 esc 退出全屏并不會觸發(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
});
}
};
使用這個之后就可以達到按下Esc鍵去修改頁面的一些狀態(tài)的目的。