为移动设备,低分辨率桌面和高分辨率桌面编写媒体查询

时间:2015-08-19 15:14:42

标签: html css mobile

我同时使用屏幕宽度和屏幕高度来检测移动设备和桌面设备之间的差异,然后检测高分辨率桌面与低分辨率桌面。

我有一些JavaScript用于加载不同的CSS文件。它看起来像这样:

的JavaScript

<script>
  if (screen.width > 800) { 

    if (screen.height < 900) { 
      document.write('<link href="/LowRes.css" type="text/css" />'); 
    } else { 
      document.write('<link href="/HiRes.css" type="text/css" />'); 
    }

} else {

    document.write('<meta name="viewport" content="width=device-width,initial-scale=1">');
    document.write('<link href="/Mobile.css" type="text/css" />'); 
}
</script>

我想改变它并使用媒体查询,这就是我所拥有的:

CSS

<link media="screen and (min-device-width: 801px) and (min-device-width: 801px)" href="low.css" rel="stylesheet" />
<link media="screen and (min-device-height: 901px)" href="hi.css" rel="stylesheet" />
<link media="screen and (max-device-width: 800px) and (orientation : portrait), screen and (max-device-height: 800px) and (orientation : landscape)" href="mobile.css" rel="stylesheet" />

这允许下载移动样式表而不管方向如何。但是,桌面样式表始终设置为高分辨率,即使它实际上是低分辨率。

enter image description here

正如您所看到的,我已经在高度800px上获得了桌面模式,媒体查询设置为min-device-height:901px,但它正在下载高分辨率样式表。这是为什么?

1 个答案:

答案 0 :(得分:2)

将所有CSS文件包含在<head>中。或者,您可以将它们组合到单个CSS文件中。

<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="/Mobile.css" type="text/css" />
<link href="/LowRes.css" type="text/css" />
<link href="/HiRes.css" type="text/css" />

然后通过将其内容包装到媒体查询来更改文件。

@media (max-width: 800px) { 
    // all contents of Mobile.css
}
@media (min-width: 801px) and (max-height:900px) { 
    // all contents of LowRes.css
}
@media (min-width: 801px) and (min-height:901px) { 
    // all contents of HiRes.css
}

查看here CSS媒体查询。作为替代方案,您可以使用nested media queries,但某些旧浏览器可能不支持它们。