使用CSS媒体查询来检测方向的最佳方法是什么? [英] What's the best way to detect orientation using CSS media queries?

查看:78
本文介绍了使用CSS媒体查询来检测方向的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用CSS @media查询来检测设备方向的最可靠方法是什么?

What's the most reliable way to detect a device's orientation using CSS @media queries?

我尝试了这些:

@media screen and (orientation: portrait)
@media screen and (orientation: landscape)

,但它们并非在所有情况下都有效. 在某些Android设备上,显示纵向模式的键盘可以使用方向:横向"查询,因为纵横比大于1/1.

but they don't work in all cases. On some Android devices, showing the keyboard in portrait mode can make it use the "orientation: landscape" query, since the aspect ratio is more than 1/1.

我已经看到建议改用它:

@media screen and (max-aspect-ratio: 13/9) // portrait
@media screen and (min-aspect-ratio: 13/9) // landscape

但是这些在iPad上的PhoneGap上不起作用;您需要一个比值更接近12/9的比率.而且我有点担心要针对这样的特定比例,因为有些设备的横向模式可能会小于该比例.

But these doesn't work on PhoneGap on the iPad; you need a ratio of something more like 12/9. And I'm a little concerned about targeting such a specific ratio, since there might be devices whose landscape mode is less than that ratio.

那么,有没有更可靠的方法来进行测试? (我只是在寻找CSS @media查询,而不是JavaScript解决方案.)

So is there a more reliable way to test this? (I'm only looking for a CSS @media query, not a JavaScript solution.)

推荐答案

我仍然想找到仅CSS的解决方案,但我想到了一种使用JavaScript生成@media查询的方法.

I'd still like to find a CSS-only solution, but I thought of a way to use JavaScript to generate the @media queries.

假设您已经可以使用JavaScript正确检测方向变化,则可以使用适当的规则动态生成style标记.当您这样做时,并且您处于纵向模式,请根据当前文档的宽度向查询添加宽度约束.例如:

Assuming you can already detect orientation changes correctly using JavaScript, you can dynamically generate a style tag with the appropriate rules. When you do, and you're in portrait mode, add a width constraint to the queries, based on the current document's width. For example:

var portraitQuery, landscapeQuery;
if (currentOrientation === "portrait") {
    portraitQuery = "@media (orientation: portrait)"
        + " or ((orientation: landscape)"
            + " and (max-width: " + (window.innerWidth) + "px))",
    landscapeQuery = "@media (orientation: landscape)"
        + " and (min-width: " + (window.innerWidth + 1) + "px)";
} else {
    portraitQuery = "@media (orientation: portrait)";
    landscapeQuery = "@media (orientation: landscape)";
}

然后,当方向改变时,重新生成这些查询.这个想法是,如果您处于纵向模式,并且@me​​dia方向更改为横向,除非宽度也增加,否则它不会开始使用横向"查询.如果仅显示键盘,则不应发生这种情况.

Then when the orientation changes, re-generate these queries. The idea is that, if you're in portrait mode and the @media orientation changes to landscape, it won't start using the "landscape" query unless the width also increases. This shouldn't happen if you're only showing the keyboard.

我不确定这有多可靠,但是到目前为止,它对我还是有用的.

I'm not sure how reliable this is, but it's working for me so far.

这篇关于使用CSS媒体查询来检测方向的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆