前言:前端展示越來(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)的目的。