在跨平台、浏览器、移动设备兼容的时候,需要根据设备、浏览器做特定调整,所以我们经常会用到navigator.userAgent.toLowerCase()来进行判断
说明:
- navigator是HTML中的内置对象:包含浏览器的信息;
- userAgent是navigator的属性方法:可以返回由客户机发送服务器的头部的值,作用其实就是就是返回当前用户所使用的是什么浏览器;
- toLowerCase是转换为小写;
区分设备是pc端还是移动端:
function _isMobile () {
let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
return flag
}
if(_isMobile()) {
alert("手机端");
this.$router.replace('/m_index');
} else {
alert("pc端");
this.$router.replace('/pc_index');
}
如移动端,判断什么系统判断是Android、HarmonyOS、ipad、iphone
var ua = navigator.userAgent.toLowerCase();
console.log(ua,'ua')
if (/android|adr/gi.test(ua)) {
alert("Android");
}else if(/HarmonyOS/gi.test(ua)){
alert('HarmonyOS')
}else if(/iPad/gi.test(ua) ){
alert("ipad");
}else if(/\(i[^;]+;( U;)? CPU.+Mac OS X/gi.test(ua)){
alert("iphone");
}
内置的浏览器,比如新浪微博、腾讯QQ(非QQ浏览器)和微信
var ua = navigator.userAgent.toLowerCase();
if(ua.match(/weibo/i) == "weibo"){
console.log('新浪微博');
}else if(ua.indexOf('qq/')!= -1){
console.log('QQ客户端');
}else if(ua.match(/MicroMessenger/i)=="micromessenger"){
console.log('微信');
var v_weixin = ua.split('micromessenger')[1];
v_weixin = v_weixin.substring(1,6);
v_weixin = v_weixin.split(' ')[0];
if(v_weixin.split('.').length == 2){
v_weixin = v_weixin + '.0';
}
if(v_weixin < '6.0.2'){
console.log('微信低于6.0.2版本');
}else{
console.log('微信高于6.0.2版本');
}
}else{
console.log('其他');
}
项目中封装的src/utils/devicePixelRatio.js文件
class devicePixelRatio {
/* 获取系统类型 */
getSystem() {
const agent = navigator.userAgent.toLowerCase()
const isMac = /macintosh|mac os x/i.test(navigator.userAgent)
if (isMac) return false
// 目前只针对 win 处理,其它系统暂无该情况,需要则继续在此添加即可
if (agent.indexOf('windows') >= 0) return true
}
/* 监听方法兼容写法 */
addHandler(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false)
} else if (element.attachEvent) {
element.attachEvent('on' + type, handler)
} else {
element['on' + type] = handler
}
}
/* 校正浏览器缩放比例 */
correct() {
// 页面devicePixelRatio(设备像素比例)变化后,计算页面body标签zoom修改其大小,来抵消devicePixelRatio带来的变化
document.getElementsByTagName('body')[0].style.zoom =
1 / window.devicePixelRatio
}
/* 监听页面缩放 */
watch() {
const that = this
// 注意: 这个方法是解决全局有两个window.resize
that.addHandler(window, 'resize', function() {
console.log('监听页面缩放')
that.correct() // 重新校正浏览器缩放比例
})
}
/* 初始化页面比例 */
init() {
const that = this
// 判断设备,只在 win 系统下校正浏览器缩放比例
if (that.getSystem()) {
console.log('初始化页面比例')
that.correct() // 校正浏览器缩放比例
that.watch() // 监听页面缩放
}
}
}
export default devicePixelRatio