基于移动或其他未知浏览器的条件


Condition based on if mobile or otherwise unknown browser

我有一个根据窗口大小响应收缩的表单。然而,我们需要它在手机和其他未知的浏览器上永远保持小。

这是伪码。jQuery也很好,我使用的是v.1.8

if ( is_desktop )
    is_narrow = false;
else
    // applies to mobile and unknown browsers
    is_narrow = true;
$( "#form" ).toggleClass( 'narrow', is_narrow );

大多数解决方案在未知浏览器上失败。例如,它们只检测浏览器是否为移动设备,否则假设浏览器为桌面设备。我需要假设移动,除非证明是一个桌面浏览器。

注:如果你想提供解决方案,我也会使用PHP

尝试使用媒体查询

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
/* Styles */
}
/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
/* Styles */
}
/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
/* Styles */
}
/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
/* Styles */
}
/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
/* Styles */
}
/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
/* Styles */
}
/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
/* Styles */
}
/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

使用此函数确定用户是否在移动设备上

 function is_mobile() {
        var agents = ['android', 'webos', 'iphone', 'ipad', 'blackberry'];
        for(i in agents) {
            if(navigator.userAgent.match('/'+agents[i]+'/i')) {
                return true;
            }
        }
        return false;
    }
if ( is_mobile )
    is_narrow = true;
else
    // applies to mobile and unknown browsers
    is_narrow = false;
$( "#form" ).toggleClass( 'narrow', is_narrow );
编辑:

你可以尝试使用这个函数:

if(jQuery.browser.mobile)
{
   console.log('You are using a mobile device!');
}
else
{
   console.log('You are not using a mobile device!');
}

您可以在CSS上做一点工作来使用Query媒体。关于HTML,您可以插入两个带有hidden/visible类属性的表单选项,它们与桌面/移动设备的某些查询媒体相关。