How do I detect when the iPhone goes into landscap

2019-01-14 17:23发布

问题:

I’m writing a web site targeted at the iPhone. I’d like to set a class on the <body> element when the iPhone’s orientation changes (i.e. when the user turns the phone into landscape and/or portrait mode).

Can I detect this change via JavaScript? Is there an event for this?

回答1:

Yup, via the onorientationchange event and the window.orientation property.

  • Documented by Apple
  • Example code on Ajaxian


回答2:

You could check the document body width. If it suddenly becomes smaller or bigger, you know what happened. You may measure it with an interval.

window.setInterval(function() {
    // check body with here and compare with global variable that holds the last measurement
    // you may set a boolean isLandscape = true if the body with became bigger.
}, 50);