在JS中检测手机角度(0,90,-90,180)的方法



我正在使用JavaScript。我需要知道用户何时更改了手机的方向,我还需要知道哪个方向(0、90、-90 或 180(。

  • 我尝试使用文档中的orientationchange
window.addEventListener("orientationchange", function(event) {
console.log("the orientation of the device is now " + event.target.screen.orientation.angle);
});

不幸的是,这在IOS Safari上不起作用。event.target.screen中没有orientation对象。

  • 我尝试使用window.orientation(似乎它正在工作,但从文档中看,它已被弃用,必须避免。

  • 我尝试resize听众.

window.onresize =  () => {
if(window.innerWidth >= window.innerHeight){
//landscape
}
else{
//portrait
}
};

这有2个问题。 1(有时,这在某些iPhone上或同一部iPhone上无法正确检测,但在不同的时间。2(我不知道如何知道角度。(0,90, -90, 180).我对屏幕和innerHeightinnerWidth之类的东西知之甚少。

有什么合适的解决方案吗?

您是否尝试过 beta(用于 x 轴(或伽马(用于 y 轴(?

例如

function handleOrientation(event) {
var absolute = event.absolute;
var alpha    = event.alpha; // z-axis
var beta     = event.beta;  // x-axis
var gamma    = event.gamma; // y-axis
// Do stuff with the new orientation data

}

您可以在窗口中使用deviceorientation事件。

window.addEventListener("deviceorientation", function(e){
const {absolute, alpha, beta, gamma} = e;
});

根据MDN:

  • DeviceOrientationEvent.alpha 值表示设备围绕 z 轴的运动,以度为单位表示,值范围为 0 到 360。
  • DeviceOrientationEvent.beta 值表示设备围绕 x 轴的运动,以度为单位表示,值范围为 -180 到 180。这表示设备的从前到后的运动。
  • DeviceOrientationEvent.gamma 值表示设备围绕 y 轴的运动,以度表示,值范围为 -90 到 90。这表示设备的从左到右运动。

最新更新