如何检测iPhone何时通过JavaScript进入横向模式? 有这个事件吗?

我正在写一个针对iPhone的网站。 我想在iPhone的方向发生变化时(即用户将手机变成横向和/或纵向模式)在<body>元素上设置一个类。

我可以通过JavaScript检测到这个变化吗? 有这个事件吗?

是的,通过onorientationchange事件和window.orientation属性。

  • 由苹果公司logging
  • Ajaxian上的示例代码

您可以检查文档的主体宽度。 如果突然变小或变大,你知道发生了什么事。 您可以间隔测量它。

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