在JavaScript中检测横屏(Landscape)和竖屏(Portrait)主要依赖于window.orientation
属性或者监听resize
事件结合window.innerWidth
和window.innerHeight
的值。以下是相关基础概念及实现方法:
window.orientation
function checkScreenOrientation() {
const orientation = window.orientation;
if (orientation === 0 || orientation === 180) {
console.log('当前为竖屏');
} else if (orientation === 90 || orientation === -90) {
console.log('当前为横屏');
}
}
// 监听屏幕方向变化
window.addEventListener('orientationchange', checkScreenOrientation);
// 初始化时检查一次
checkScreenOrientation();
resize
事件function checkScreenOrientation() {
const width = window.innerWidth;
const height = window.innerHeight;
if (width > height) {
console.log('当前为横屏');
} else {
console.log('当前为竖屏');
}
}
// 监听窗口大小变化
window.addEventListener('resize', checkScreenOrientation);
// 初始化时检查一次
checkScreenOrientation();
window.orientation
属性。可以通过检测window.screen.orientation
作为替代方案。window.orientation
属性。可以通过检测window.screen.orientation
作为替代方案。resize
事件:在屏幕方向变化时,resize
事件可能会频繁触发,可以通过节流(throttle)或防抖(debounce)技术来优化性能。resize
事件:在屏幕方向变化时,resize
事件可能会频繁触发,可以通过节流(throttle)或防抖(debounce)技术来优化性能。通过以上方法,可以有效地检测和处理屏幕方向的变化,提升用户体验。
领取专属 10元无门槛券
手把手带您无忧上云