为手机加载不同的CSS(但不适用于平板电脑)

时间:2015-09-28 22:01:10

标签: css jquery-mobile mobile media-queries device-detection

我需要为手机加载不同的CSS样式表,但不适用于平板电脑。我过去使用以下解决方案:

<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="viewport" content="width=480">
<link rel="stylesheet" media="only screen and (max-width: 480px)"href="mobile.css" />
<link rel="stylesheet" media="only screen and (min-width: 481px)" href="desktop.css" />

或:

@media only screen and (max-width: 480px) {
}

但两者都基于屏幕分辨率。今天大多数手机使用更高的分辨率,因此它不会像我想的那样工作,原因如下:平板电脑也会受到这部分的影响:

<meta name="viewport" content="width=480">

我希望平板电脑像台式机/笔记本电脑一样。

另外,我试图这样做:

var IS_IPHONE = navigator.userAgent.match(/iPhone/i) != null;
var IS_ANDROID = navigator.userAgent.match(/Android/i)  != null;

if(IS_IPHONE)    ({
      url: href,
      dataType: 'css',
      success: function(){                  
            $('<link rel="stylesheet" type="text/css" href="'+css/iphone.css+'" />').appendTo("head");
        }
});

if(IS_ANDROID)    ({
      url: href,
      dataType: 'css',
      success: function(){                  
            $('<link rel="stylesheet" type="text/css" href="'+css/android.css+'" />').appendTo("head");
        }
});

但是现在有很多不同的手机,我无法搜索每个可能的设备并且偶尔添加它。 此外,Androids现在也是平板电脑。

是否有任何GENERIC代码可以检测智能手机(不是平板电脑,只是手机)? 我想它不能基于媒体查询。

我试图找到基于当前帖子的解决方案,但我的问题没有明确的答案,所以我在这里发布了。

由于

1 个答案:

答案 0 :(得分:0)

Mobile Detect是一种非常简单有效的检测设备的PHP方法 - https://github.com/serbanghita/Mobile-Detect

简单来说:

/ Include and instantiate the class.
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;

// Any mobile device (phones or tablets).
if ( $detect->isMobile() ) {

}

// Any tablet device.
if( $detect->isTablet() ){

}

// Exclude tablets.
if( $detect->isMobile() && !$detect->isTablet() ){

}

您可以在发布和更新过程中使用composer,以确保您拥有最新的Mobile_Detect版本。

composer require mobiledetect/mobiledetectlib

{
    "require": {
        "mobiledetect/mobiledetectlib": "^2.8"
    }
}
相关问题