使用js實現移動設備訪問跳轉到指定目錄

最近最項目的時候總會同時作pc站點跟手機站點,當手機訪問的時候默認是看到pc站點的,須要在url上加上/mobile才能正常訪問,這段代碼是我同事分享給個人,仍是蠻實用的.javascript

CODEjava

function ckMobile() {
    var browser = {
        versions: function () {
            var u = navigator.userAgent, app = navigator.appVersion;
            return {
                trident: u.indexOf('Trident') > -1, //IE內核                
                presto: u.indexOf('Presto') > -1, //opera內核                
                webKit: u.indexOf('AppleWebKit') > -1, //蘋果、谷歌內核                
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐內核                
                mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否爲移動終端                
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios終端                
                android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android終端或者uc瀏覽器               
                iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否爲iPhone或者QQHD瀏覽器                
                iPad: u.indexOf('iPad') > -1, //是否iPad                
                webApp: u.indexOf('Safari') == -1 //是否web應該程序,沒有頭部與底部            
            };
        } ()
    }

    if (browser.versions.mobile || browser.versions.iPhone) {
        if (!browser.versions.iPad || (document.body.clientWidth < 450)) {
            return true;
        }
    }
}


function ckGoogleBrowser() {
    var Sys = {};
    var ua = navigator.userAgent.toLowerCase();
    var s;
    (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
    (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
    (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
    (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
    (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
    if (Sys.chrome != null || Sys.opera != null || Sys.firefox != null) { return true; }
   
}


function CheckBrowser() {
    if (!ckGoogleBrowser()) {
        if (ckMobile()) {
            location.href = "/mobile/";
        }
    }
}


CheckBrowser();

  

備註:在站點起始頁引用便可.android

相關文章
相關標籤/搜索