网站开发过程中总会碰到客户端是否是手机端还是PC端,那如何判断页面是在移动端还是PC端打开的呢?
首先来了解一下Navigator 对象,Navigator 对象包含有关浏览器的信息,下面的userAgent 属性是一个只读的字符串,声明了浏览器用于 HTTP 请求的用户代理头的值。所以我们可以通过判断navigator.useragent里面是否有某些值来判断。看如下代码:
if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) { window.location.href = "http://sucai.gxyourui.cn/Mobile/Article/blog"; } else { window.location.href = "http://sucai.gxyourui.cn/Home/Article/blog"; }
如图:
您还可以使用如下代码来判断:
(function browserRedirect(){
var sUserAgent = navigator.userAgent.toLowerCase();
var bIsIpad = sUserAgent.match(/ipad/i) == 'ipad';
var bIsIphone = 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) == 'web';
var bIsCE = sUserAgent.match(/windows ce/i) == 'windows ce';
var bIsWM = sUserAgent.match(/windows mobile/i) == 'windows mobile';
var bIsAndroid = sUserAgent.match(/android/i) == 'android';
if(bIsIpad || bIsIphone || bIsMidp || bIsUc7 || bIsUc || bIsCE || bIsWM || bIsAndroid ){
window.location.href = “http://sucai.gxyourui.cn/mobile/Article/blog”
}
})();
具体详情可前往http://sucai.gxyourui.cn/Home/Article/blog_detail/article_id/48.html查看