我见过很多检测设备屏幕方向的方法,包括使用检查 innerWidth 和 innerHeight 的值进行比较,例如:
function getOrientation(){
var orientation = window.innerWidth > window.innerHeight ? "Landscape" : "Primary";
return orientation;
}
但是如果我想使用事件监听器检测屏幕方向的变化,该怎么办呢?我尝试了这段代码,但它对我无效。
function doOnOrientationChange()
{
switch(window.orientation)
{
case -90:
case 90:
alert('landscape');
break;
default:
alert('portrait');
break;
}
}
window.addEventListener('orientationchange', doOnOrientationChange);
// Initial execution if needed
doOnOrientationChange();
它无法检测设备方向,而且监听器无法为我注册(我正在使用Chrome的设备模拟器)。