帮助中心 >  技术知识库 >  网站相关 >  建站知识 >  百度判断手机终端并自动跳转uaredirect.js代码及使用实例

百度判断手机终端并自动跳转uaredirect.js代码及使用实例

2017-05-11 14:38:49 6006

刚好另一个站点需要 手机访问跳转到手机模版 就拿出来了 顺便记录下!
js代码如下:

function uaredirect(f) {
try {
if (document.getElementById("bdmark") != null) {
return
}
var b = false;
if (arguments[1]) {
var e = window.location.host;
var a = window.location.href;
if (isSubdomain(arguments[1], e) == 1) {
f = f + "/#m/" + a;
b = true
} else {
if (isSubdomain(arguments[1], e) == 2) {
f = f + "/#m/" + a;
b = true
} else {
f = a;
b = false
}
}
} else {
b = true
}
if (b) {
var c = window.location.hash;
if (!c.match("fromapp")) {
if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i))) {
location.replace(f)
}
}
}
} catch(d) {}
}
function isSubdomain(c, d) {
this.getdomain = function(f) {
var e = f.indexOf("://");
if (e > 0) {
var h = f.substr(e + 3)
} else {
var h = f
}
var g = /^www\./;
if (g.test(h)) {
h = h.substr(4)
}
return h
};
if (c == d) {
return 1
} else {
var c = this.getdomain(c);
var b = this.getdomain(d);
if (c == b) {
return 1
} else {
c = c.replace(".", "\\.");
var a = new RegExp("\\." + c + "$");
if (b.match(a)) {
return 2
} else {
return 0
}
}
}
};

    

    使用方法

    保存以上代码为uaredirect.js,将这个JS文件的引用最好放到网站的title下,不要放在最后或者其他部位,这样做是因为会先加载uaredirect.js后跳转,这样做会很快,如果先加载其他的JS或者CSS的话,会先加载它们再跳转,这样跳转速度就会很慢了。加载的话,只需要一段代码就OK了。

例如:http://www.landui.com/ 是手机版的网站, http://www.landui.com/是电脑版的网站。

推荐大家用 压缩后的代码
function uaredirect(f){try{if(document.getElementById("bdmark")!=null){return}var b=false;if(arguments[1]){var e=window.location.host;var a=window.location.href;if(isSubdomain(arguments[1],e)==1){f=f+"/#m/"+a;b=true}else{if(isSubdomain(arguments[1],e)==2){f=f+"/#m/"+a;b=true}else{f=a;b=false}}}else{b=true}if(b){var c=window.location.hash;if(!c.match("fromapp")){if((navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i))){location.replace(f)}}}}catch(d){}}function isSubdomain(c,d){this.getdomain=function(f){var e=f.indexOf("://");if(e>0){var h=f.substr(e+3)}else{var h=f}var g=/^www\./;if(g.test(h)){h=h.substr(4)}return h};if(c==d){return 1}else{var c=this.getdomain(c);var b=this.getdomain(d);if(c==b){return 1}else{c=c.replace(".","\\.");var a=new RegExp("\\."+c+"$");if(b.match(a)){return 2}else{return 0}}}};


提交成功!非常感谢您的反馈,我们会继续努力做到更好!

这条文档是否有帮助解决问题?

非常抱歉未能帮助到您。为了给您提供更好的服务,我们很需要您进一步的反馈信息:

在文档使用中是否遇到以下问题: