前提提要:项目类似于单点登录,所开发项目属于iframe嵌套展示。最外层框架使用了dv-full-screen-container实现全屏展示(左侧和上测菜单栏还存在),不满足现在需求,因此采用了如下方法。
1.实现全屏
<template>
<div ref="container" >
<!-- Your content here -->
<button @click="toggleFullScreen">{{ifFullScan?'全屏':'退出'}}</button>
</div>
</template>
<script>
export default {
name: 'DvFullScreenContainer',
data(){
ifFullScan: false
},
methods: {
toggleFullScreen() {
const container = this.$refs.container;
this.ifFullScan = !this.ifFullScan;
if (!document.fullscreenElement) {
// The element is not in fullscreen mode.
if (container.requestFullscreen) {
container.requestFullscreen();
} else if (container.mozRequestFullScreen) { /* Firefox */
container.mozRequestFullScreen();
} else if (container.webkitRequestFullscreen) { /* Chrome, Safari and Opera */
container.webkitRequestFullscreen();
} else if (container.msRequestFullscreen) { /* IE/Edge */
container.msRequestFullscreen();
}
} else {
// The element is already in fullscreen mode.
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) { /* Firefox */
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) { /* Chrome, Safari and Opera */
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) { /* IE/Edge */
document.msExitFullscreen();
}
}
},
},
};
</script>
现在问题来了,使用esc退出时,无法触发ifFullScan的变化,导致点击esc触发还原后,按钮展示的为“退出”。
2.实现使用ESC触发还原,更改ifFullScan状态
(1)常用监测方法—无法实现监测esc操作
export default {
data() {
return {
// ...
};
},
methods: {
onEsc(event) {
if (event.key === 'Escape' || event.keyCode === 27) {
console.log('Esc key pressed');
// 在这里处理 Esc 按键的行为
}
},
},
mounted() {
document.addEventListener('keydown', this.onEsc);
},
beforeUnmount() {
document.removeEventListener('keydown', this.onEsc);
},
};
(2)最终实现方法
<template>
<div ref="container" >
<!-- Your content here -->
<button @click="toggleFullScreen">{{ifFullScan?'全屏':'退出'}}</button>
</div>
</template>
<script>
export default {
data() {
return {
elementWidth: 0,
elementHeight: 0,
resizeObserver: null,
ifFullScan:false,
};
},
methods: {
handleResize(entries) {
const entry = entries[0];
if(entry.contentRect.height < this.elementHeight ){
this.ifFullScan = false;
}
this.elementWidth = entry.contentRect.width;
this.elementHeight = entry.contentRect.height;
},
//单独对某个dom元素进行监测时可使用
toggleResizeObserver() {
if (!this.resizeObserver) {
this.startObserving();
} else {
this.stopObserving();
}
},
startObserving() {
this.resizeObserver = new ResizeObserver((entries) => {
this.handleResize(entries);
});
this.resizeObserver.observe(this.$refs.container);
},
stopObserving() {
this.resizeObserver.disconnect();
this.resizeObserver = null;
},
},
mounted() {
// 可以在这里初始化 ResizeObserver,如果需要始终监听
// this.startObserving();
},
beforeDestroy() {
if (this.resizeObserver) {
this.stopObserving();
}
},
};
</script>