JavaScript在Safari浏览器中的屏幕方向

17

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

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

    angulo = screen.orientation || screen.mozOrientation || screen.msOrientation;
    
    Example angulo.angle

它返回 0,但不能在 Safari 中使用,只能在 MSF 和 Chrome 中使用。在 Safari 中它显示:

TypeError: undefined is not an object (evaluating 'angulo.angle')

我能做什么?


你是否正在尝试确定设备是处于竖屏模式还是横屏模式? - Rachel Gallen
angulo = 之前,执行 screen = screen || window; - Washington Guedes
2个回答

32

如果您需要角度来确定页面是纵向还是横向模式,则使用以下代码:

document.addEventListener("orientationchange", updateOrientation);

你也可以使用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
    }
});

或者您可以使用resize事件。

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

}, false);

David Walsh的有用文章中,提供了更多提示(但可能还有其他在SO上的例子)


2
非常感谢,window.matchMedia帮了我大忙。 - SrAxi
我很乐意接受。但是这个问题不是我创建的。我只是从你的答案中受益并点赞了你的回答。 - SrAxi
1
@SrAxi 抱歉,我应该仔细看一下。很高兴它能帮到不止一个人:)。感谢您的投票,祝一切顺利... - Rachel Gallen
2
如果在IFRAME中,这可能无法正常工作。这意味着window.matchMedia("(orientation: portrait)");将基于IFRAME的高度和宽度比而不是屏幕。因此,只能在父框架中使用。 - claudiomedina
2
截至2022年9月,这是跨平台方向检测的方法。在Safari支持screen.orientation上的change事件之前,请使用此方法。谢谢。 - katalin_2003

10

2
这真是太遗憾了,因为 (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/ - user2875289
3
如果它已被弃用,在Safari iOS上如何获取方向更改后的方向? - Dimitri Kopriwa
1
仅仅因为它已经被弃用并不意味着你不能使用它。只是可能在某个时候会被移除。 - sparkyspider

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接