js判断当前设备是否为移动端
背景
响应式布局:随着移动互联网的发展,用户通过手机和平板访问网页的比例越来越高。为了提供更好的用户体验,开发者需要根据设备类型调整页面布局、字体大小、图片尺寸等,以确保在不同屏幕尺寸上都有良好的显示效果。
交互方式差异:移动设备和桌面设备的交互方式有很大不同(例如触控屏 vs 鼠标点击),因此需要针对不同的交互方式进行适配。
编码实战
/*** 判断当前设备是否为移动设备(包括手机、平板、微信小程序 WebView 等)* @returns {boolean} 是否为移动端*/
function isMobileDevice() {// 获取浏览器的 User-Agent 字符串,用于识别操作系统、浏览器类型等信息const ua = navigator.userAgent || navigator.vendor || window.opera;/*** 检测是否是常见的移动设备* 匹配关键词:Android、iPhone、iPad、iPod、BlackBerry、webOS、Windows Phone、SymbianOS、IEMobile、Opera Mini* 适用于大多数主流手机和平板设备*/const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|webOS|Windows Phone|SymbianOS|IEMobile|Opera Mini/i.test(ua);/*** 检测是否是平板设备(如 iPad、Kindle Fire、黑莓 PlayBook 等)* 特别处理了 Amazon Fire 平板的特征码 KFxxx* 注意:iPadOS 在桌面 Safari 中 UA 可能显示为 Macintosh,所以补充了 touch 关键词检测*/const isTablet = /ipad|playbook|silk|(android.*\bkf[a-z]{2,6}\b)|kindle|macintosh.*touch/i.test(ua);/*** 检测设备是否支持触控屏* 使用多种方式兼容不同浏览器:- 'ontouchstart' in window:标准触控事件是否存在- navigator.maxTouchPoints:多点触控支持数量(现代浏览器)- navigator.msMaxTouchPoints:IE 和旧版 Edge 兼容*/const hasTouchScreen = (('ontouchstart' in window) ||(navigator.maxTouchPoints > 0) ||(navigator.msMaxTouchPoints > 0));/*** 判断是否是 PC 端的微信环境(用于后续排除 PC 微信误判)* 如果 UA 中包含 Windows NT 或 Macintosh,则认为是桌面端微信*/const isPcInWeChat = /Windows NT|Macintosh/.test(ua);/*** 判断是否是微信内置浏览器或小程序 WebView* 但需要排除 PC 微信的情况(否则可能误判为移动端)*/const isWeChatWebView = /micromessenger/i.test(ua) && !isPcInWeChat;/*** 判断是否是从微信小程序加载的 Web 页面(可选)* 小程序加载 web-view 时可以通过 URL 参数传递标志位* 示例:<web-view src="https://yourdomain.com/page?from=miniprogram" />*/const isInMiniProgram = /from=miniprogram/.test(window.location.search);/*** 最终判断逻辑:* 满足以下任意条件即判定为“移动端”:** 1. 是常见移动设备(如 Android、iPhone)* 2. 是平板设备(如 iPad、Kindle)* 3. 支持触控屏,并且窗口宽度小于 1024px(模拟移动端体验)* 4. 是微信小程序 WebView(非 PC 环境)* 5. 是从微信小程序加载的页面(通过 URL 参数识别)*/return isMobile || isTablet || (hasTouchScreen && window.innerWidth < 1024) || isWeChatWebView || isInMiniProgram;
}
无注释版本
function isMobileDevice() {const ua = navigator.userAgent || navigator.vendor || window.opera;const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|webOS|Windows Phone|SymbianOS|IEMobile|Opera Mini/i.test(ua);const isTablet = /ipad|playbook|silk|(android.*\bkf[a-z]{2,6}\b)|kindle|macintosh.*touch/i.test(ua);const hasTouchScreen = (('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0));const isPcInWeChat = /Windows NT|Macintosh/.test(ua);const isWeChatWebView = /micromessenger/i.test(ua) && !isPcInWeChat;const isInMiniProgram = /from=miniprogram/.test(window.location.search); // 如果你控制了 URLreturn isMobile || isTablet || (hasTouchScreen && window.innerWidth < 1024) || isWeChatWebView || isInMiniProgram;
}