Safari 上的 Javascript 屏幕方向

El *_*cto 11 javascript iphone safari screen-orientation

我正在尝试制作一个响应式网站,它几乎完成了,但我需要帮助。

我正在使用这个例子来了解角度:

    angulo = screen.orientation || screen.mozOrientation || screen.msOrientation;
    
    Example angulo.angle
Run Code Online (Sandbox Code Playgroud)

它返回 0,但它不适用于 Safari,仅适用于 MSF 和 Chrome。在 Safari 中,它显示:

TypeError: undefined is not an object (evaluating 'angulo.angle')
Run Code Online (Sandbox Code Playgroud)

我能做什么?

Rac*_*len 14

如果您需要角度来确定您的页面是纵向模式还是横向模式,请使用以下方法:

document.addEventListener("orientationchange", updateOrientation);
Run Code Online (Sandbox Code Playgroud)

你也可以使用 matchMedia

var mql = window.matchMedia("(orientation: portrait)");

// If there are matches, we're in portrait
if(mql.matches) {  
    // Portrait orientation
} else {  
    // Landscape orientation
}

// Add a media query change listener
mql.addListener(function(m) {
    if(m.matches) {
        // Changed to portrait
    }
    else {
        // Changed to landscape
    }
});
Run Code Online (Sandbox Code Playgroud)

或者你可以使用一个resize事件

window.addEventListener("resize", function() {
    // Get screen size (inner/outerWidth, inner/outerHeight)

}, false);
Run Code Online (Sandbox Code Playgroud)

David Walsh 的方便文章中有更多提示(但可能还有其他关于 SO 的示例)

  • 非常感谢,`window.matchMedia`救了我。 (2认同)
  • 如果在 IFRAME 内,这可能不起作用。这意味着 `window.matchMedia("(orientation: Portrait)");` 将基于 IFRAME 的高宽比,而不是屏幕。因此,您可以在父框架中使用。 (2认同)
  • 截至 2022 年 9 月,这是跨平台方向检测的方式。直到Safari支持“screen.orientation”上的“change”事件。谢谢。 (2认同)

Bat*_*ley 7

Safari/Safari iOS(又名新 IE6)不支持 screen.orientation api。您必须改用 window.orientation (这不是有效的属性)

示例:http : //www.williammalone.com/articles/html5-javascript-ios-orientation/

  • 如果已弃用,在 safari ios 上更改方向后如何获取方向? (3认同)
  • 这是一个很大的耻辱,因为 (1) `window.orientation` 已被弃用。https://developer.mozilla.org/en-US/docs/Web/API/Window/orientation (2) 不保证您能得到您想要的结果。https://www.matthewgifford.com/2015/07/11/a-misconception-about-window-orientation/ (2认同)
  • 仅仅因为它已被弃用并不意味着您不能使用它。它可能会在某个时候被删除。 (2认同)