全屏Hooks
/**
* 全屏Hooks
* @param {*} fullScreenEle 全屏的元素
* @returns
*/
export const useFullScreen = ({ fullScreenEle = document.documentElement }) => {
/**
* 遍历执行兼容的方法
* @param {*} methodList 方法列表
* @param {*} element 全屏元素
*/
const eachCompatibleMethod = (methodList, element) => {
for (let i = 0; i < methodList.length; i++) {
const method = methodList[i];
if (method) {
method.call(element);
break;
}
}
};
// 获取正在全屏的元素
const getFullScreeningElement = () => {
// 正在全屏的元素
const {
fullscreenElement,
webkitFullscreenElement,
mozFullScreenElement,
webkitIsFullScreen,
mozFullScreen,
} = document;
return (
fullscreenElement ||
webkitFullscreenElement ||
mozFullScreenElement ||
webkitIsFullScreen ||
mozFullScreen
);
};
// 退出全屏
const exitFullScreen = () => {
// 退出全屏的兼容方法
const {
webkitExitFullscreen,
mozCancelFullScreen,
exitFullscreen,
msRequestFullscreen,
} = document;
// 退出全屏的方法列表
const exitFullscreenMethods = [
webkitExitFullscreen,
mozCancelFullScreen,
exitFullscreen,
msRequestFullscreen,
];
eachCompatibleMethod(exitFullscreenMethods, document);
};
// 全屏
const launchFullScreen = () => {
const {
requestFullscreen,
mozRequestFullScreen,
webkitRequestFullScreen,
msExitFullscreen,
} = document.documentElement;
// 全屏的方法列表
const fullScreenMethods = [
requestFullscreen,
mozRequestFullScreen,
webkitRequestFullScreen,
msExitFullscreen,
];
if (!unref(fullScreenEle)) return;
eachCompatibleMethod(fullScreenMethods, unref(fullScreenEle));
};
// 切换全屏
const toggleFullScreen = () => {
// 正在全屏的元素
const fullScreeningElement = getFullScreeningElement();
if (fullScreeningElement) {
// 退出全屏
exitFullScreen();
} else {
// 全屏
launchFullScreen();
}
};
// 监听全屏状态变化
const listenFullScreen = fullScreenChange => {
const fullscreenChangeMethods = [
'fullscreenchange',
'webkitfullscreenchange',
'mozfullscreenchange',
'msfullscreenchange',
];
let element = unref(fullScreenEle);
if (!element) return;
fullscreenChangeMethods.forEach(method => {
element.addEventListener(method, fullScreenChange);
});
};
return {
getFullScreeningElement,
exitFullScreen,
launchFullScreen,
toggleFullScreen,
listenFullScreen,
};
};