【问题标题】:Loading different CSS for mobile phones (but not for tablets)为手机加载不同的 CSS(但不适用于平板电脑)
【发布时间】:2015-09-28 22:01:10
【问题描述】:

我需要为手机加载不同的 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");
        }
});

但是现在有这么多不同的手机,我无法搜索所有可能的设备并偶尔添加它。 此外,如今的安卓也是平板电脑。

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

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

谢谢

【问题讨论】:

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


    【解决方案1】:

    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"
        }
    }
    

    【讨论】:

    • 谢谢。有没有服务器外的解决方案?也许是 jquery?
    • 你可以在 jquery 中检测代理,但它有点移动目标所以我不推荐。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多