Vue full screen solution

Today I remembered that an interview question was about how to operate the page in full screen, hereby summarize a wave of knowledge points I have learned

1. Original

The native provides two ways to realize the full screen operation of the page

_1, Document.exitFullscreen() This method requests to switch from full-screen mode to window mode, and its return value is a promise object, which will be set to resolved state after all full-screen modes are closed.

_2, Element.requestFullscreen() This method requests the browser to turn a specific element, even its descendants, into full-screen mode, and hide all UI on the page, as well as other applications. Its return value is also a promise object, in full-screen mode When activated, it will be set to the resolved state.

 But the native writing method is too cumbersome, and the api is not very easy to use.

Fullscreen API - Web API Interface Reference | MDN    Native Interface Documentation

2. Plug-ins

screenfull plugin

Install 

npm install --save screenfull

 import

import screenfull from "screenfull";

Then we use his method toggle, screefull.toggle() to switch the full-screen mode. This method must use a UI to trigger it, and then we can also use screenfull.isEnabled() to determine whether the browser supports full-screen.

According to our logic, when the browser switches to full screen, some UI or components will change its current state, and fullscreen also provides us with a method similar to an event listener, screenfull.onchange(callback), to register a Listen for events, and trigger the corresponding callback when switching full screen or switching window mode. He also has another way of writing, screenfull.on('change', callback). In js, we also use on to bind events. Of course, we also use off to log out of listening events.

When we bind a listener event, we need a browser state, otherwise we cannot know what state our callback function acts on. We can use screen.isFullscreen to determine whether the browser is in a global state.

3、Vue

import {  ref } from "vue";

//判断浏览器是否支持全屏
let isSupport=document.fullscreenEnabled
//给全屏一个判断状态,全屏时为true,窗口为false
let isFull=ref(false)
//监听全屏状态,在浏览器支持全屏的条件下,当前元素是否是全屏
//document.fullscreenElement 当前展示为全屏模式的元素
const screenchange = () => {
	if (isSupport) {
		document.fullscreenElement ? isFullscreen.value = true : isFullscreen.value = false
	}
};
//注册监听
document.addEventListener("fullscreenchange", screenchange , true);

//点击 切换屏幕状态
const togggle=()=>{
if (isSupport) {
		if (document.fullscreenElement) {
            //document.exitFullscreen()退出全屏模式的方法
			document.exitFullscreen();
			isFullscreen.value = false;
		} else {
			//requestFullscreen(),请求全屏的方法
			document.documentElement.requestFullscreen();
			isFullscreen.value = true;
		}
	}

}

Guess you like

Origin blog.csdn.net/qq_45662523/article/details/126652264