2011-08-08 34 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>