项目上客户有PC端网页,也有专门开发的手机端网址,同一个入口网址可以减少客户的学习成本,也是一种很好的手段,根据客户使用的客户端来自动跳转就可以了,每个浏览器在发送请求的头部里面都会有识别设备类型的User Agent可以设置,手机,pad等就跳转到移动端网页,PC电脑端就跳转到PC端页面,提供良好的用户体验。
上代码:
<script type="text/javascript">
var commonURL = 'http://www.freexyz.cn';
function mobile_device_detect(url){
var thisOS=navigator.platform;
var os=new Array("iPhone","iPod","iPad","android","Nokia","SymbianOS","Symbian","Windows Phone","Phone","Linux armv71","MAUI","UNTRUSTED/1.0","Windows CE","BlackBerry","IEMobile");
for(var i=0;i<os.length;i++){
if(thisOS.match(os[i])){
window.location=url;
}
}
if(navigator.platform.indexOf('iPad') != -1){
window.location=url;
}
var check = navigator.appVersion;
if( check.match(/linux/i) ){
if(check.match(/mobile/i) || check.match(/X11/i)) {
window.location=url;
}
}
Array.prototype.in_array = function(e){
for(i=0;i<this.length;i++){
if(this[i] == e)
return true;
}
return false;
}
}
mobile_device_detect("http://www.freexyz.cn/Mobile/");/*指定跳转地址*/
</script>
方法一:纯JS判断
<script type=”text/javascript”>
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
window.location = “mobile.html”; //可以换成http地址
}
</script>
使用这方法既简单,又实用,不需要引入jQuery库,把以下代码加入到head标签里即可
方法二:使用 Device.Js 库
device.js 是一个用于检查设备用的插件,使用它你可以很方便的判断设备的操作系统,以及设备是纵向还是横向。
首先,我们下载Device.js
下载地址:https://github.com/matthewhudson/device.js
STEP 1: 引入 JS 文件
<script src=”device.min.js”></script>
STEP 2: 加入判断代码
Device.js 方法有很多,若你想实现对某个设备的判断,要以根据以下代码来替换device.mobile()。

以上两种方法判断手机端都是很实用的,由其是电脑版网页和手机版网页分别用不同的网站域名时,使用该方法可以免去用户记2个域名烦恼!
判断访问者使用的设备,如果是手机客户端访问PC端网页则自动跳转到移动端页面。
JS代码:
<script type="text/javascript">
(function(W){
if(/iphone|nokia|sony|ericsson|mot|samsung|sgh|lg|philips|
panasonic|alcatel|lenovo|cldc|midp|wap|
mobile/i.test(navigator.userAgent.toLowerCase())){
W.location.href = '跳转地址';
}
})(window)
</script>
