【问题标题】:Way to detect angle (0, 90, -90, 180) of the phone in JSJS中检测手机角度(0、90、-90、180)的方法
【发布时间】:2020-07-04 20:13:22
【问题描述】:

我正在使用 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
    }
};

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

任何适当的解决方案?

【问题讨论】:

    标签: javascript ios safari


    【解决方案1】:

    您是否尝试过 beta(用于 x 轴)或 gamma(用于 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
    

    }

    【讨论】:

    • orientationchange 事件给了我event,但你提到的那个对象没有绝对或任何其他属性。
    【解决方案2】:

    您可以在窗口上使用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。这表示设备从左到右的运动。

    【讨论】:

    • 感谢您的精彩回答。我遇到的问题是,即使我接受了方向更改事件的许可,也可以使用 `DeviceOrientationEvent.requestPermission(), It still doesn't call deviceorientation` 事件。可能是因为我在本地测试这个(在自签名证书上?)或者它在 safari ios 模拟器上不起作用?
    猜你喜欢
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    相关资源
    最近更新 更多