[英]How to detect device orientation with JavaScript?
我已经看到了很多方法来检测设备的屏幕方向,包括使用检查来测试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的设备模拟器)。
有两种方法可以做到这一点:
首先,根据Screen API文档,使用> = Chrome 38,Firefox和IE 11,屏幕对象不仅可以查看方向,还可以在每次设备方向更改时注册侦听器。
screen.orientation.type
将明确告诉您方向是什么,对于侦听器,您可以使用以下简单的内容:
screen.orientation.onchange = function (){
// logs 'portrait' or 'landscape'
console.log(screen.orientation.type.match(/\w+/)[0]);
};
其次,为了与Safari等与Screen不兼容的其他浏览器兼容, 本文显示您可以继续在窗口大小调整时使用innerWidth和innerHeight。
function getOrientation(){
var orientation = window.innerWidth > window.innerHeight ? "Landscape" : "Portrait";
return orientation;
}
window.onresize = function(){ getOrientation(); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.