2012-09-24 157 views
0

我刚刚从本机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 
    } 
} 

或者,如果它不是合适的方式做设计的东西,那么我该怎么做呢?

+0

为什么你要比较的屏幕宽度?是否将iPod/iPhone与iPad比较?或者,是因为另一个原因? – Littm

回答

1

它严重依赖于你想要做什么。如果您打算根据设备的分辨率或屏幕方向更改逻辑或添加/删除DOM元素,请使用JS方式。如果你正在使用jQuery它的那样简单,因为这:

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

然而,CSS本身取决于屏幕尺寸条件样式提供了途径。这些被称为media-querieshttp://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

+0

我最终解决了这个问题!谢谢! –

0

鉴于PhoneGap将Web应用程序封装到本机shell中,您基本上正在进行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

0

我想你可以试试下面的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);