确定设备类型
我们经常需要这样做,在手机上显示 A 逻辑,在 PC 上显示 B 逻辑。基本上,设备类型是通过识别浏览器的userAgent来确定的。
判断设备是Android还是IOS
除了区分是手机端还是PC端,很多时候我们还需要区分当前设备是Android还是IOS。
代码展示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
html,
body {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="message" style="color: red;"></div>
<div>判断当前是移动设备还是桌面设备</div>
<div id="msg" style="color: red;"></div>
<div>判断当前设备是Android还是ios</div>
</body>
<script>
// 判断是什么设备
const isMobile = () => {
return !!navigator.userAgent.match(
/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i
);
};
const message = document.querySelector('#message');
if (isMobile()) {
message.textContent = '您正在使用移动设备。';
} else {
message.textContent = '您正在使用桌面设备。';
}
const isAndroid = () => {
return /android/i.test(navigator.userAgent.toLowerCase());
};
const isIOS = () => {
let reg = /iPhone|iPad|iPod|iOS|Macintosh/i;
return reg.test(navigator.userAgent.toLowerCase());
};
const msg = document.querySelector('#msg');
if (isAndroid()) {
msg.textContent = '当前设备是 Android';
} else {
// msg.textContent = '当前设备不是 Android';
console.log('当前设备不是 Android');
}
if (isIOS()) {
msg.textContent = '当前设备是 iOS';
} else {
// msg.textContent = '当前设备不是 iOS';
console.log('当前设备不是 iOS');
}
</script>
</html>