Tumblr上的移动设备检测

时间:2015-11-12 22:56:32

标签: javascript jquery html css tumblr

我正在尝试创建一个Tumblr主题,如果用户在iOS上(带有应用商店链接),则会显示一个div,如果用户在其他任何内容(使用其他链接),则会显示一个。但是,由于Tumblr的工作方式,我无法弄清楚为什么它不起作用。我尝试使用https://www.mattcromwell.com/detecting-mobile-devices-javascript/,这是用Wordpress编写的,我不太明白我在tumblr中缺少什么。

<script type="text/javascript">
    var isMobile = { 
    iOS: function() { return navigator.userAgent.match(/iPhone|iPad|iPod/i); }, 
    any: function() { return (isMobile.iOS();} };
</script>

是我在head标签中的内容。然后,我需要在页脚中进行实际检测,我有

<p id="is-mobile" class="hide">This is a Mobile Device</p>
<p id="is-desktop" class="hide">This is NOT a Mobile Device</p>
<script type="text/javascript"> 
    jQuery(function($) {
         if (!isMobile.iOS())
             $('#is-mobile').addClass('show');
         if (isMobile.iOS())
             $('#is-desktop').addClass('show');
    });
</script>

也许我在错误的地方有其他jQuery?我也导入了jQuery库。希望有人可以帮助我!当我这样做时,它从不显示任何div而不管设备(显然因为我隐藏它们 - 而且我确实在css中有一个不显示.hide类的东西)。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

正如@Shikkediel指出的那样,iOS功能似乎存在问题。

我做了这个小提琴。我也认为可能需要反转的条件(至少现在在桌面上显示桌面的div,而只在移动设备上显示移动设备)。

https://jsfiddle.net/lharby/fvau9vnz/

这是代码:

var isMobile = { 
    iOS: function() { 
        return navigator.userAgent.match(/iPhone|iPad|iPod/i)
    }, 
    any: function() { 
        return (isMobile.iOS())
    } 
};

jQuery(function($) {
    if (isMobile.iOS()){ // we should only need an if/else here now. Changed from !isMobile.iOS(); 
        $('#is-mobile').addClass('show');
    }else{
        $('#is-desktop').addClass('show');
    }
});

答案 1 :(得分:0)

Tumblr允许自定义CSS,不是吗?

您可以按照设备屏幕尺寸进行操作,因此您不必依赖用户代理(可能spoofed和/或有时不工作)。

像这样的东西(CSS):

#is-mobile{ /* Hide it by default */
    display:none;
}
@media screen and (max-width: 500px){
    #is-mobile{ /* If the screen is <= 500px, display it */
        display:block;
    }
}

我对Tumblr的工作方式并不熟悉,但这就是我在正常网页设计中检测移动设备的方式。

对于基于每个设备的媒体查询check this out

More info on the css @media rule