Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在JS中检测手机角度(0,90,-90,180)的方法_Javascript_Ios_Safari - Fatal编程技术网

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

Javascript 在JS中检测手机角度(0,90,-90,180)的方法,javascript,ios,safari,Javascript,Ios,Safari,我正在使用JavaScript。我需要知道用户何时更改了手机的方向,我还需要知道是哪个方向(0、90、-90或180) 我试图使用文档中的orientationchange 不幸的是,这在IOS Safari上不起作用。event.target.screen中没有orientation对象 我试着使用了window.orientation(它似乎在工作,但从文档中看,它已被弃用,必须避免使用) 我尝试了调整监听器的大小 这有两个问题。1)有时在某些iPhone或同一部iPhone上无

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

  • 我试图使用文档中的
    orientationchange
不幸的是,这在IOS Safari上不起作用。
event.target.screen
中没有
orientation
对象

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

  • 我尝试了调整监听器的大小

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

有合适的解决方案吗?

您是否尝试过β(用于x轴)或γ(用于y轴)

e、 g


}

您可以使用窗口上的
deviceorientation
事件

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

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

orientationchange事件为我提供了
事件
,但您提到的对象上没有绝对属性或任何其他属性。谢谢您的回答。我遇到的问题是,即使我接受了方向更改事件的许可,通过使用`DeviceOrientationEvent.requestPermission()
,它仍然不会调用`deviceorientation`事件。这可能是因为我正在本地(在自签名证书上)测试它,还是因为它在SafariIOS模拟器上无法工作?
window.onresize =  () => {
    if(window.innerWidth >= window.innerHeight){
          //landscape
     }
    else{
        //portrait
    }
};
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
window.addEventListener("deviceorientation", function(e){
    const {absolute, alpha, beta, gamma} = e;
});