2011-08-08 46 views
0

我有一个JavaScript代码重定向手机用户。你可以检查代码,我从网上捡起来,总newb,我会重视你对脚本质量的输入...Javascript代码重定向手机用户

它是否涵盖所有类型的手机?

function RedirectSmartphone(url) { 
    if (url && url.length > 0 && IsSmartphone()) 
     window.location = url; 
} 

function IsSmartphone() { 
    if (DetectUagent("android")) return true; 
    else if (DetectUagent("iphone")) return true; 
    else if (DetectUagent("ipod")) return true; 
    else if (DetectUagent("symbian")) return true; 
    return false; 
} 

function DetectUagent(name) { 
    var uagent = navigator.userAgent.toLowerCase(); 
    if (uagent.search(name) > -1) 
     return true; 
    else 
     return false; 
} 
RedirectSmartphone("http://mobile.version.com"); 
+2

http://detectmobilebrowser.com/将为您生成代码,如果你想。我以前使用过他们的代码,它工作得很好。 – dtanders

+0

我不知道。我个人会检查屏幕分辨率,而不是嗅探用户代理。这样你就可以在不同的屏幕上显示正确的页面/样式。 –

+0

是否涵盖所有类型的手机? **否。**关于黑莓,WebOS和Windows Phone 7(仅举几例)? – Greg

回答

3

具体取决于“所有电话”的含义,但不包括例如黑莓手机或平板电脑。

更好的方法是检测屏幕分辨率,例如,在jQuery的你可以这样做:

if ((screen.width < 1024) && (screen.height < 768)) { 
window.location = 'http://mobile.site.com'; 
} 
+0

Id喜欢它覆盖平板电脑,黑莓 – webmasters

+0

平板电脑?!移动版本的网站总是吸引10英寸的屏幕。 – Quentin

+0

Ty非常适合代码,使得分辨率更有意义。请问您可以使用重定向编辑代码,以便说出http://mobile.mysite.com? – webmasters

0

我认为它涵盖了所有手机。但想提供几个简单的方法来清除代码。

function IsSmartphone(){ 
    return (DetectUagent("android") || DetectUagent("ipod") || DetectUagent("ipod") || DetectUagent("symbian")); 
} 

function DetectUagent(name){ 
    return (navigator.userAgent.toLowerCase().search(name) > -1); 
} 
+0

看起来方式更清洁...我应该使用它,它可靠吗?我想确定是因为我的一些收入将取决于它 – webmasters

+0

测试您正在寻找的所有设备。这将给你100%的信心:) – ShankarSangoli

+0

只是请做优化这个可怕的脚本... – Denis

5

我在我的网站上运行下面的代码(显然有轻微的修改),它似乎与Android,iPad,iPhone和黑莓的工作相当不错。我为我的PHP页面使用了一个PHP版本,并且为我的CGI/PERL页面使用了这些代码,两者都具有相同的效果。

<script type="text/javascript"> 
function RedirectSmartphone(url){ 
    if (url && url.length > 0 && IsSmartphone()) 
    window.location = url; 
} 
function IsSmartphone(){ 
    if (DetectUagent("android")) return true; 
    else if (DetectUagent("blackberry")) return true; 
    else if (DetectUagent("iphone")) return true; 
    else if (DetectUagent("opera")) return true; 
    else if (DetectUagent("palm")) return true; 
    else if (DetectUagent("windows")) return true; 
    else if (DetectUagent("generic")) return true; 
    else if (DetectUagent("ipad")) return true; 
    else if (DetectUagent("ipod")) return true; 
    return false; 
} 
function DetectUagent(name){ 
    var uagent = navigator.userAgent.toLowerCase(); 
    if (uagent.search(name) > -1) 
    return true; 
    else 
    return false; 
} 
RedirectSmartphone("http://mobile.version.com"); 
</script>