82 lines
2.3 KiB
JavaScript
82 lines
2.3 KiB
JavaScript
|
|
/**
|
|||
|
|
* 屏幕方向管理工具类
|
|||
|
|
* 用于检测和处理屏幕方向变化
|
|||
|
|
*/
|
|||
|
|
export default {
|
|||
|
|
/**
|
|||
|
|
* 监听屏幕方向变化
|
|||
|
|
* @param {Function} callback 方向变化时的回调函数
|
|||
|
|
* @returns {Object} 包含remove方法的对象,用于移除监听
|
|||
|
|
*/
|
|||
|
|
onOrientationChange(callback) {
|
|||
|
|
// 监听window的orientationchange事件
|
|||
|
|
const handleOrientationChange = () => {
|
|||
|
|
const orientation = window.orientation || 0;
|
|||
|
|
const isLandscape = Math.abs(orientation) === 90;
|
|||
|
|
const isPortrait = orientation === 0 || orientation === 180;
|
|||
|
|
|
|||
|
|
callback({
|
|||
|
|
orientation,
|
|||
|
|
isLandscape,
|
|||
|
|
isPortrait
|
|||
|
|
});
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
window.addEventListener('orientationchange', handleOrientationChange);
|
|||
|
|
|
|||
|
|
// 立即执行一次回调,获取当前方向
|
|||
|
|
handleOrientationChange();
|
|||
|
|
|
|||
|
|
// 返回移除监听的方法
|
|||
|
|
return {
|
|||
|
|
remove: () => {
|
|||
|
|
window.removeEventListener('orientationchange', handleOrientationChange);
|
|||
|
|
}
|
|||
|
|
};
|
|||
|
|
},
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取当前屏幕方向
|
|||
|
|
* @returns {Object} 包含orientation、isLandscape、isPortrait属性的对象
|
|||
|
|
*/
|
|||
|
|
getCurrentOrientation() {
|
|||
|
|
const orientation = window.orientation || 0;
|
|||
|
|
return {
|
|||
|
|
orientation,
|
|||
|
|
isLandscape: Math.abs(orientation) === 90,
|
|||
|
|
isPortrait: orientation === 0 || orientation === 180
|
|||
|
|
};
|
|||
|
|
},
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 请求全屏显示
|
|||
|
|
* 对于视频播放等场景很有用
|
|||
|
|
* @param {HTMLElement} element 要全屏显示的元素,默认为document.documentElement
|
|||
|
|
*/
|
|||
|
|
requestFullscreen(element = document.documentElement) {
|
|||
|
|
if (element.requestFullscreen) {
|
|||
|
|
element.requestFullscreen();
|
|||
|
|
} else if (element.mozRequestFullScreen) {
|
|||
|
|
element.mozRequestFullScreen();
|
|||
|
|
} else if (element.webkitRequestFullscreen) {
|
|||
|
|
element.webkitRequestFullscreen();
|
|||
|
|
} else if (element.msRequestFullscreen) {
|
|||
|
|
element.msRequestFullscreen();
|
|||
|
|
}
|
|||
|
|
},
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 退出全屏
|
|||
|
|
*/
|
|||
|
|
exitFullscreen() {
|
|||
|
|
if (document.exitFullscreen) {
|
|||
|
|
document.exitFullscreen();
|
|||
|
|
} else if (document.mozCancelFullScreen) {
|
|||
|
|
document.mozCancelFullScreen();
|
|||
|
|
} else if (document.webkitExitFullscreen) {
|
|||
|
|
document.webkitExitFullscreen();
|
|||
|
|
} else if (document.msExitFullscreen) {
|
|||
|
|
document.msExitFullscreen();
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
};
|