方法一
<script type="text/javascript"> function browserRedirect() { var sUserAgent = navigator.userAgent.toLowerCase(); var bIsIpad = sUserAgent.match(/ipad/i) == "ipad"; var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os"; var bIsMidp = sUserAgent.match(/midp/i) == "midp"; var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4"; var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb"; var bIsAndroid = sUserAgent.match(/android/i) == "android"; var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce"; var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile"; if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) { document.writeln("phone"); } else { document.writeln("pc"); } } browserRedirect(); </script>
方法二
<script> var url = location.search; url = url.substr(1); var bs={ 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, //是否为iPhone或者QQHD浏览器 iPad: u.indexOf('iPad') > -1 //是否iPad }; }(), language:(navigator.browserLanguage || navigator.language).toLowerCase() } if(bs.versions.mobile && url!='mobile'){ if(bs.versions.android||bs.versions.iPhone||bs.versions.iPad||bs.versions.ios){ window.location.href="跳转的手机地址"; }else{
window.location.href="跳转的pc地址";
}
}
</script>
两者都是一样的原理,利用javascript中navigator对象下的userAgent属性来做判断只是两者的返回一个是indexOf一个是match。
一般情况下我们还会有另外一个需求就是电脑当前地址跳转到手机对应地址,比如www.baidu.com/news对应的是m.baidu.com/news这个时候用截取替换掉主域名即可。
var current_url = window.location.href;//获取当前连接 //str2是被替换的链接str3替换后的链接 function replaceAll(current_url ,str2,str3){ var k; var tmp = str1.split(str2); k=tmp[0]; for(i=1;i<tmp.length;i++){ k+=str3+tmp[i]; } return k; }