What's the best way to detect orientation usin

2019-04-17 02:29发布

问题:

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

I tried these:

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

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.

I've seen suggestions to use this instead:

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

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.

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

回答1:

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

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)";
}

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.



回答2:

I'm not a pro with orientation but maybe you can have both conditions for the landscape orientation like:

@media screen and (min-aspect-ratio: 13/9), screen and (orientation:landscape)