说明:
实测可以在谷歌、火狐、360 浏览器使用
解决了在浏览器全屏下监听不到键盘Esc事件
解决了取消全屏和全屏的同步问题,ESC按键下可以同步
代码如下:
- html片段
<!-- 全屏显示 -->
<div class="btn-fullscreen" @click="handleFullScreen">
<el-tooltip effect="dark" :content="fullscreen?`取消全屏`:`全屏`" placement="bottom">
<i class="el-icon-rank"></i>
</el-tooltip>
</div>
- vue片段
data() {
return {
fullscreen: false,
}
},
mounted() {
const _this = this;
window.addEventListener('resize', () => {
if(!_this.checkFull()) {
// 退出全屏后要执行的动作
_this.fullscreen = false;
}
})
},
methods: {
checkFull() {
//判断浏览器是否处于全屏状态 (需要考虑兼容问题)
//火狐浏览器
//谷歌浏览器及Webkit内核浏览器
var isFull = document.mozFullScreen || document.fullScreen || document.webkitIsFullScreen ||
document.webkitRequestFullScreen || document.mozRequestFullScreen || document.msFullscreenEnabled;
if (isFull === undefined) {
isFull = false;
}
return isFull;
},
// 控制浏览器是否全屏
changeScreen() {
let element = document.documentElement;
if(this.fullscreen) {
if(document.exitFullscreen) { //W3C
document.exitFullscreen();
} else if (document.mozCancelFullScreen) { //FireFox
document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) { //Chrome等
document.webkitCancelFullScreen();
} else if (document.msExitFullscreen) { //IE11
document.msExitFullscreen();
}
} else {
if(element.requestFullscreen) { //W3C
element.requestFullscreen();
} else if (element.webkitRequestFullScreen) { //Chrome等
element.webkitRequestFullScreen();
} else if (element.mozRequestFullScreen) { //FireFox
element.mozRequestFullScreen();
} else if (element.msRequestFullscreen) { //IE11
element.msRequestFullscreen();
}
}
this.fullscreen = !this.fullscreen;
},
}
vue的mounted中window.onresize不生效
原因: 在vue开发中,因为引用的父组件和子组件都使用了window.onresize以至于一个window.onresize失效。
解决方案: 可以采用下面的方式
let that = this
window.onresize = function() { if(!that.checkFull())that.fullscreen = false; }
// 改为以下写法
window.addEventListener('resize', () => {
if(!that.checkFull())that.fullscreen = false;
});
网友评论