【问题标题】:Mobile device responsive design layout移动设备响应式设计布局
【发布时间】:2012-09-24 15:44:43
【问题描述】:

我刚刚从原生 iOS 开发人员迁移到跨平台。我正在使用 phonegap,我想根据设备屏幕尺寸和方向创建不同的布局。 我想做的是类似于这段代码的东西

if(orientation == LANDSCAPE)
{
    if(screen.width < 320)
    {
        //use css #1
    }
    else
    {
        //use css #2
    }
}
else //orientation is PORTRAIT
{
    if(screen.width < 320)
    {
        //use css #3
    }
    else
    {
        //use css #4
    }
}

或者,如果这不是适当的设计方式,那我该怎么做?

【问题讨论】:

  • 为什么要比较屏幕宽度?是用来比较 iPod/iPhone 和 iPad 的吗?还是有别的原因?

标签: jquery cordova jquery-mobile


【解决方案1】:

这很大程度上取决于你想做什么。如果您打算根据设备的分辨率或屏幕方向更改逻辑或从 DOM 中添加/删除元素,请使用 JS 方式。如果您使用的是 jQuery,它就这么简单:

var deviceWidth = $(window).width();
var deviceHeight = $(window).height();

然而,CSS 本身提供了根据屏幕大小设置条件样式的方法。这些称为media-queries (http://www.w3.org/TR/css3-mediaqueries/),您可以按如下方式使用它们:

@media only screen and (max-device-width: 480px) {
    body {
        font-size: 2em;
        /* etc. these styles will be applied only when device's screen is smaller than 480px */
    }
}

您可以使用更多属性。 max-device-width 只是一个例子。 此外,如果设备尺寸不合适,您可以完全阻止浏览器加载样式文件:

<link rel="stylesheet" media="only screen and (max-width-device: 480px)" href="480-device.css" />

查看 w3c 文档或搜索 media-queries。它们现在几乎兼容所有浏览器:http://caniuse.com/#feat=css-mediaqueries

【讨论】:

    【解决方案2】:

    鉴于 PhoneGap 将 Web 应用程序包装到本地外壳中,此时您实际上是在进行 Web 开发。您需要查看media queries。对于您发布的代码,相应的媒体查询类似于以下内容:

    /* Landscape */
    @media screen and (orientation: landscape) {
        /* Landscape styles */
    }
    
    /* Portrait */
    @media screen and (orientation: portrait) {
        /* Portrait styles */
    }
    
    /* Portrait and screen width < 320 */
    @media screen 
    and (orientation: portrait)
    and (max-width: 320px) {
        /* Portrait styles for screen smaller than 320 pixels */
    }
    

    媒体查询规范说您应该能够嵌套媒体查询,这将更紧密地匹配您的控制语句的结构,但是unfortunately most modern browsers do not yet support this

    【讨论】:

      【解决方案3】:

      我想你可以试试下面的JS代码:

      function _orientationHandler() {
          if(event.orientation){
              if(event.orientation == 'portrait'){
                  if(screen.width < 320)
                  {
                      //use css #1
                  }
                  else
                  {
                      //use css #2
                  }
          }
          else if(event.orientation == 'landscape') {
              if(screen.width < 320)
              {
                  //use css #1
              }
              else
              {
                  //use css #2
              }
          }
      }
      
      $(window).bind('orientationchange', _orientationHandler);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-10
        • 2018-09-20
        • 2019-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-25
        相关资源
        最近更新 更多