检测设备方向

Detect device orientation

运行一个响应式单页应用,有内容的盒子对象。这些旨在具有背景图像。然而,对于手持设备,方向成为一个问题,因为框的宽度和高度比例会发生变化。

检测设备和视口大小并不是建立在统一程序之上的任务。在我看来,假设用户拥有相对现代的浏览器,CSS3 并调用 @media screen and (orientation:landscape) 是最安全的选择。

假设图像将在水平和垂直版本中裁剪,并且标签使用无方向编码

<div class="box" style='background:  url("https://somewhere.amazonaws.com/general-purpose-images/splash.jpg") no-repeat fixed; background-size: 100% 100%; background-attachment: scroll;'>

如何根据方向有效切换?

为图像设置 div 和 class

<div class="img_a">

然后根据方向为所需图像定义 CSS 规则,或者 any other media queries 您可能需要实施

@media screen and (orientation: portrait)
  { div.img_a 
      { background: url(https://[...]img_a.jpg) no-repeat fixed; }
  [...] }
@media screen and (orientation: landscape)
  { div.img_a 
      { background: url(https://[...]img_a_horizontal.jpg) no-repeat fixed; }
  [...] }