手机访问 PC 网站自动跳转到手机网站
一、实现思路
如果手机直接访问 PC 站页面,如果页面没有做自适应的情况下,在手机上浏览电脑版网站体验非常不好。如果能够手机访问 PC 端页面自动跳转到手机页面就好了,其实也很好实现。代码如下:
将以下代码放在首页区
<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.xxx.com");
</script>
倒数第二行中的 http://m.xxx.com 就是要跳转到的手机版网址。
可能有人会觉得上面的方法太复杂了,简单一点的JS代码如下:
<script type="text/javascript">
try {
var urlhash = window.location.hash;
if (!urlhash.match("fromapp"))
{
if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iPad)/i)))
{
window.location="http://m.xxx.com/";
}
}
}
catch(err)
{
}
</script>
第三款代码:
<script type="text/javascript">
// JavaScript Document
function urlredirect() {
var sUserAgent = navigator.userAgent.toLowerCase();
if ((sUserAgent.match(/(ipod|iphone os|midp|ucweb|android|windows ce|windows mobile)/i))) {
// PC跳转移动端
var thisUrl = window.location.href;
window.location.href = thisUrl.substr(0,thisUrl.lastIndexOf('/')+1)+'mobile/';
}
}
urlredirect();
</script>
其他
function IsPC()
{
var userAgentInfo = navigator.userAgent;
var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
var flag = true;
for (var v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; }
}
return flag;
}
function goPAGE() {
if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
window.location.href="你的手机版地址";
} else {
window.location.href="你的电脑版地址"; }
}
goPAGE();
二、实例
自动检测访问端是PC还是手机的代码,PC端访问跳转手机 与手机跳转到PC
function mobile_device_detect(url) {
var sUserAgent = navigator.userAgent.toLowerCase();
if ((sUserAgent.match(/(ipod|iphone os|midp|ucweb|android|windows ce|windows mobile)/i))) {
window.location = url;
}
}
function pc_device_detect(url) {
var sUserAgent = navigator.userAgent.toLowerCase();
if (!(sUserAgent.match(/(ipod|iphone os|midp|ucweb|android|windows ce|windows mobile)/i))) {
window.location = url;
}
}