【问题标题】:Change CSS Based on Mobile Orientation根据移动方向更改 CSS
【发布时间】:2011-11-11 23:30:43
【问题描述】:

当移动应用程序页面方向从横向更改为纵向(反之亦然)时,更改 css 文件的最佳方法是什么。我只需要同时支持 Android 和 iPhone。似乎媒体查询不是最干净的方式,还有其他想法吗?

【问题讨论】:

  • 没有任何选项可以绑定到窗口调整大小事件,如果 X 大于 Y 则为横向? Y 比 X 大,你有肖像吗?将 1 var 保留为布尔值,isLandscape,如果更改,请编辑样式表?
  • 为什么你认为 CSS 媒体查询不是干净的解决方案?

标签: javascript android iphone mobile


【解决方案1】:

例子

/* 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;
  }
}

更多详情见here

【讨论】:

  • @Mike 欢迎。如果投票支持我的回答,您可以表示感谢。
  • np 刚刚做了一次 txs
【解决方案2】:

下面的 JQuery 代码似乎最适合我……绑定示例没有。

$(document).ready(function() {
               $(window).resize(function() {
                  alert(window.orientation);
                  });
               });

【讨论】:

    【解决方案3】:

    首先给你的样式表包含一行 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 你是对的(固定)。我读错了一些东西。无论如何,这个/应该/在手机浏览器上工作。
    【解决方案4】:

    您可以使用 window.onorientationchange 事件。

    【讨论】:

      猜你喜欢
      • 2013-09-15
      • 1970-01-01
      • 2013-04-15
      • 1970-01-01
      • 2011-06-19
      • 2017-01-31
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      相关资源
      最近更新 更多