在开发中会判断客户端是移动端还是pc来做一个响应式布局,在原生js中可以根据bom的navigator对象userAgent属性来获取浏览器用户代理信息,在用户代理信息中会包含浏览器的型号
在浏览器中运行
console.log(navigator.userAgent);
//Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0
户代理信息:Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0
Firefox/89.0便是浏览器型号信息
当我们获取用户代理信息,我们便可以通过正则匹配常见的移动端浏览器型号来判断客户端浏览器型号了
function isMobile() {
return navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
},
如果只是想提醒用户该页面只适配了移动端,建议用户去移动吨访问时,在vue中:
methods: {
isMobile() {
return navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
},
},
created() {
if (!this.isMobile()&&screen.availWidth >500) {
alert("该页面只适配了移动端样式,如需完好体验,请去移动端访问,或者在浏览器中按ctrl+shift+m");
}
},