三种检测iPhone/iPad设备方向的方法

  使用meta tag "viewport"

  viewport标签包含如下属性:

三种检测iPhone/iPad设备方向的方法

  为了能自动探测并适配到屏幕宽度,应该使用device-with而不是设定一个固定值,另外为了避免用户缩放导致界面超出屏幕,需要设置maximum-scale,

  

复制代码 代码如下:

  <meta name="viewport" content="width=device-width, maximum-scale=1.0" />

  使用javascript脚本

  下面的脚本通过检测屏幕宽度来检测方向并调整方向:

  

复制代码 代码如下:

  <script type="text/javascript">

  var updateLayout = function() {

  if (window.innerWidth != currentWidth) {

  currentWidth = window.innerWidth;

  var orient = (currentWidth == 320) ? "profile" : "landscape";

  document.body.setAttribute("orient", orient);

  window.scrollTo(0, 1);

  }

  };

  iPhone.DomLoad(updateLayout);

  setInterval(updateLayout, 400);

  </script>

  上述脚本可放在head部分

  使用CSS

  使用CSS的media query:

  

复制代码 代码如下:

  <link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">

  <link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">