在JavaScript中监听手机横屏主要涉及到window
对象的orientation
属性以及resize
事件。以下是相关基础概念及实现方法:
window.orientation
可以返回当前设备的屏幕方向。0
(竖屏)、90
或-90
(横屏)、180
(倒置竖屏)。resize
事件。orientationchange
事件window.addEventListener('orientationchange', function() {
if (window.orientation === 90 || window.orientation === -90) {
console.log('当前为横屏');
// 在此处添加横屏时的处理逻辑
} else {
console.log('当前非横屏');
// 在此处添加非横屏时的处理逻辑
}
});
resize
事件判断function checkOrientation() {
const width = window.innerWidth;
const height = window.innerHeight;
if (width > height) {
console.log('当前为横屏');
// 在此处添加横屏时的处理逻辑
} else {
console.log('当前非横屏');
// 在此处添加非横屏时的处理逻辑
}
}
// 监听resize事件
window.addEventListener('resize', checkOrientation);
// 初始化时检查一次方向
checkOrientation();
orientationchange
事件。resize
事件进行判断,以提高兼容性。resize
事件可能会频繁触发。function throttle(func, delay) {
let timer = null;
return function() {
if (!timer) {
timer = setTimeout(() => {
func.apply(this, arguments);
timer = null;
}, delay);
}
};
}
function checkOrientationThrottled() {
const width = window.innerWidth;
const height = window.innerHeight;
if (width > height) {
console.log('当前为横屏');
} else {
console.log('当前非横屏');
}
}
window.addEventListener('resize', throttle(checkOrientationThrottled, 200));
checkOrientationThrottled(); // 初始化检查
通过上述方法,你可以有效地在JavaScript中监听并响应手机的横屏状态。
没有搜到相关的文章