前端技巧:精准判断登录设备是移动端还是PC端
在前端开发过程中,判断用户的登录设备究竟是移动端还是PC端,这一需求极为常见。比如,为了给用户提供更适配的页面布局和交互体验,我们就需要知晓设备类型。下面就为大家详细介绍几种判断设备类型的方法。
原生JS判断设备类型的方法
方案一:基于navigator.userAgent的User Agent检测
通过navigator.userAgent,我们可以获取到浏览器的标识字符串。然后利用正则表达式,去匹配那些代表移动端设备的关键词,像android、iphone、mobile等等。如果匹配成功,那就意味着当前设备是移动端,反之则为PC端。实现代码如下:
function isMobileDevice() {
const ua = navigator.userAgent || navigator.vendor || window.opera;
const mobileRegex = /android|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile|windows phone|phone|webos|kindle|tablet/i;
return mobileRegex.test(ua.toLowerCase());
}

最低0.47元/天 解锁文章
1083

被折叠的 条评论
为什么被折叠?



