JS判断移动端并自动跳转至移动端网站

作者: 时间:
浏览 : 738

分享一个保哥经常使用的JS移动设备浏览器判断及自动跳转代码,实现当手机或平板等移动端打开网站时会自动跳转至手机版网站。第一种方法,具体代码如下:

<SCRIPT LANGUAGE="JavaScript">
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;
}
//做这一部分是因为Android手机的内核也是Linux
//但是navigator.platform显示信息不尽相同情况繁多,因此从浏览器下手,即用navigator.appVersion信息做判断
var check = navigator.appVersion;
if( check.match(/linux/i) )
{
//X11是UC浏览器的平台 ,如果有其他特殊浏览器也可以附加上条件
if(check.match(/mobile/i) || check.match(/X11/i))
{
window.location=url;
} 
}
//类in_array函数
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://m.zhangwenbao.com");
</SCRIPT>

 

复制以上代码放在<head>与</head>中间,将网址m.zhangwenbao.com改为你自己的二级域名手机端网址即可。

还有一种更简洁的代码如下:

<script type="text/javascript">
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
window.location = "wap.html"; //可以换成http地址
}
</script>

 

第二种方法,使用Device.Js库。device.js是一个用于检查设备用的插件,使用它你可以很方便的判断设备的操作系统,以及设备是纵向还是横向。下载地址:https://github.com/matthewhudson/device.js

<script src="device.js"></script>
<script type="text/javascript">
if(device.mobile()){
window.location = "wap.html"; //可以换成http地址
}
</script>

以上保哥分享的两种用于判断手机端的方法都是很实用的,尤其是PC站和手机站有不同的域名时,使用该方法可以免去用户记2个域名的烦恼!

Tag标签:

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注