js判断页面是在pc端或移动端打开

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30109365/article/details/81013389

1.问题出现的原因,

pc端官网在移动端打开。一方面不兼容,另一方面不好看(看着怪怪的),所以想让pc端打开跳到专门的pc端网站上,移动端打开跳到专门的移动端网站,

2.解决方案

代码一:

window.location.href = /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent) ? “https://www.baidu.com/” : “http://news.baidu.com/“;

代码二:

if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)){
window.location.href = “https://www.baidu.com/“;
} else {
window.location.href = “http://news.baidu.com/“;
}

3.原理

Navigator对象
Navigator 对象包含有关浏览器的信息,下面的userAgent 属性是一个只读的字符串,声明了浏览器用于 HTTP 请求的用户代理头的值。所以我们可以通过判断navigator.useragent里面是否有某些值来判断,比如我的电脑是mac,所以打印出来的值为

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36

.test 做匹配
window.location.href 跳转

猜你喜欢

转载自blog.csdn.net/qq_30109365/article/details/81013389