前言:前端展示越来越重要,随着可视化图表的功能越来越强大。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 };
使用时只需要导入即可
(由于我做的是一个后台管理项目,这里全屏会区别于别的一些项目。这里想说的其实是全屏监听Esc键来达到修改数据的目的)
使用时遇到一个问题 :全屏状态下按下Esc键,需要修改页面数据。不然状态不改变会出问题。
监听Esc键
// 这是一个demo
componentDidMount() {
this.bindFullscreenListener ();
}
componentWillUnmount() {
try {
this.unBindFullscreenListener();
} catch (e) {
console.warn(e);
}
}
bindFullscreenListener = () => {
// 监听退出全屏事件 --- chrome 用 esc 退出全屏并不会触发 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键去修改页面的一些状态的目的。
网友评论