如何为移动设备应用不同的 CSS,而不仅仅是基于媒体宽度/高度



我想为移动设备、手机和平板电脑的某些元素显示不同的 CSS 样式,但不同宽度的媒体查询效果不佳,因为假设我的手机和 17 英寸笔记本电脑都具有相同的全高清分辨率,而现代平板电脑的分辨率比大多数台式机显示器都大......

所以我想为安卓,iPhone/iPad,黑莓,Windows移动设备(手机/平板电脑)应用CSS样式。

有什么办法吗?

你可以做的一件事是通过测试userAgent,使用javascript将自定义类应用于html元素或body元素。

见下文:

在jQuery中检测移动设备的最佳方法是什么?因此,您的解决方案将如下所示。

.JS

/*
see the link above for other user agents. 
you could come up with a bit more sophisticate solution 
I'm sure but this would be a quick implementation.
*/
<script type="text/javascript">
//test if droid

if( /Android/i.test(navigator.userAgent) ) {
    $('body').addClass('device_android');
}
</script>

.CSS

<style>
//css styles for android
.device_android element #id .orclass {
    //some styles for android specific styling here
}
</style>

请记住,虽然这是针对通用设备的,但这并不能解决操作系统版本和浏览器等的变化,这在许多情况下被证明是 js 和 css 错误的原因。

if ((getResources().getConfiguration().screenLayout & 
Configuration.SCREENLAYOUT_SIZE_LARGE) == Configuration.SCREENLAYOUT_SIZE_LARGE ||
(getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_XLARGE)
    ==          Configuration.SCREENLAYOUT_SIZE_XLARGE ){
        System.out.println('In Tablet');
    }else {
        System.out.println('In Phone');
    }

媒体查询不仅可以使用宽度。您还可以使用方向甚至设备像素比。因此,如果您处理诸如视网膜显示器之类的内容,那么您可以或多或少地编写如下:

@media only screen 
   and (min-device-width : xxx px) 
   and (max-device-width : xxx px) 
   and (orientation : landscape or portrait)
   and (min-resolution: xxx dpi){ 
   // your css goes here
}

在这里查看网络工具包的具体示例!

相关内容

最新更新