最近项目开发中遇到一个视频窗口全屏切换功能,为此在这里做个记录。
具体的实现思路:
javascript
<template>
<div class="content-box">
<div class="container">
<div id="screen" class="screen">
<el-button @click="screen()">
{{ fullscreen ? "还原" : "最大化" }}
</el-button>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
fullscreen: false,
};
},
mounted() {
window.addEventListener("resize", ()=> {
if (!this.isFullScreen()) {
// 非全屏状态
this.fullscreen = false;
}
});
},
methods: {
//判断是否全屏
isFullScreen() {
return !!(document.webkitIsFullScreen || this.fullele());
},
fullele() {
return (
document.fullscreenElement ||
document.webkitFullscreenElement ||
document.msFullscreenElement ||
document.mozFullScreenElement ||
null
);
},
screen() {
let element = document.getElementById("screen");
if (this.fullscreen) {
// 关闭全屏
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
} else {
// 全屏
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.webkitRequestFullScreen) {
element.webkitRequestFullScreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.msRequestFullscreen) {
// IE11
element.msRequestFullscreen();
}
}
this.fullscreen = !this.fullscreen;
},
},
};
</script>
<style lang="scss" scoped>
.screen {
width: 500px;
height: 500px;
background-color: #fff;
border: 1px solid red;
}
</style>
这里需要监听ESC键,为此做了特殊处理,这里是Demo,跟使用效果图基本差不多