根据移动设备方向改变CSS

4

当移动应用程序页面方向从横向变为纵向或者相反方向时,改变CSS文件的最佳方法是什么?我需要支持Android和iPhone。似乎媒体查询不是最干净的方法,还有其他的想法吗?


有没有绑定到窗口调整大小事件的选项,如果X比Y大,则为横向?如果Y比X大,则为纵向?保持一个变量作为布尔值,isLandscape,如果它被更改,则编辑您的样式表? - Niels
1
你为什么认为CSS媒体查询不是一个干净的解决方案? - Wojciech Bednarski
4个回答

7

示例

/* For portrait */
@media screen and (orientation: portrait) {
  #toolbar {
    width: 100%;
  }
}

/* For landscape */

@media screen and (orientation: landscape) {
  #toolbar {
    position: fixed;
    width: 2.65em;
    height: 100%;
  }

  p {
    margin-left: 2em;
  }
}

更多详细信息请参见此处


@Mike 欢迎。如果您投票支持我的答案,您可以表达您的感激之情。 - isxaker
1
没有问题,刚刚完成了,再次感谢。 - Mike

1
首先,在你的样式表包含行中添加一个id="cssElement"或类似的内容。
然后使用jQuery:
$(document).ready(function(){   

   // The event for orientation change
   var onChanged = function() {

      // The orientation
      var orientation = window.orientation;

      if(orientation == 90) { 
          $('#cssElement').attr('href', '/path/to/landscape.css');
      } else {
          $('#cssElement').attr('href', '/path/to/portrait.css');
      }

   };

   // Bind the orientation change event and bind onLoad
   $(window).bind(orientationEvent, onChanged).bind('load', onChanged);

});

我以为 window.orientation 是一个数字,而不是一个字符串。 - icktoofay
^^icktoofay 您是正确的(已修复)。我读错了一些内容。无论如何,在手机浏览器上,这个/应该/能够正常工作。 - Rick Kukiela

1
以下的 JQuery 代码对我来说似乎是最好的选择...绑定的例子并不适用。
$(document).ready(function() {
               $(window).resize(function() {
                  alert(window.orientation);
                  });
               });

0

你可以使用 window.onorientationchange 事件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接