在移动WEB开发中,有些场景需要判断设备的横竖屏状态,在发现orientation方法之前我用的是获取设备的宽高来判断:
//判断横竖屏
$(window).resize(() => {
let w = $("body").width();
let h = $("body").height();
if (w > h) {
alert("横屏");
}else{
alert("竖屏");
}
})
$(window).resize();
最近发现js判断移动设备横竖屏有原生方法:
//判断横竖屏
function VorH() {
if (window.orientation == 90 || window.orientation == -90) {
return "横向";
} else if (window.orientation == 0 || window.orientation == 180) {
return "竖向";
}
}
// 添加事件监听
addEventListener('load', function(){
VorH();
window.onorientationchange = VorH;
});
感谢阿豹的分享:http://www.best-html5.net/?p=661