移动设备响应式设计布局

时间:2012-09-24 07:20:53

标签: jquery cordova jquery-mobile

我刚刚从原生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
    }
}

或者如果不适合进行设计,那我该怎么做呢?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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);
相关问题