现在很多网站都有PC端和移动端,同一个URL根据设备跳转到不同页面的方法,可以用JS脚本,也可以用后台代码的正则去判断
1,JS
//根据操作系统跳转
$(function(){
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) {
window.location.href = 'mobile设备地址';
} else {
window.location = 'PC设备地址';
}
})
后台判断如下
string u = Request.ServerVariables["HTTP_USER_AGENT"];
Regex b=new Regex(@"android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge|maemo|midp|mmp|netfront|operam(ob|in)i|palm(os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino|ucweb|mqqbrowser", RegexOptions.IgnoreCase | RegexOptions.Multiline);
if (b.IsMatch(u))
{
Response.Redirect("mobile设备地址");
}
else
{
Response.Redirect("PC设备地址");
}
浏览器访问页面时,会发出叫HTTP_USER_AGENT的服务器变量请求。请求中会带上浏览器的信息。通过正则表达式匹配,如果浏览器信息中带有正则中的任意一项,则匹配手机页面成功,跳转到手机页面。如果都不能匹配,就会跳转到电脑页面。正则表达式中的信息为现有手机浏览器信息,以后随着手机浏览器花样不断翻新,需要不断往里面添加表达式项。