上一篇
场景引入:
"小王正用手机浏览公司官网,结果打开的是电脑版页面!😫 字体小得要用放大镜,按钮间距窄得能玩'手指芭蕾'... 这时候如果网站能自动识别手机并跳转移动版,体验直接起飞!🛫"
console.log(navigator.userAgent); // 输出示例(iPhone): // "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15..."
这就是设备的"身份证"!通过它我们能判断:
function checkMobile() { const ua = navigator.userAgent.toLowerCase(); const isMobile = /iphone|ipod|android|windows phone/.test(ua); if(isMobile && !location.href.includes('/m/')) { window.location.href = 'https://你的域名.com/m'; } } // 页面加载时执行 window.addEventListener('DOMContentLoaded', checkMobile);
function deviceRedirect() { const ua = navigator.userAgent; const isMobile = /Mobile|iP(hone|od)|Android|BlackBerry/.test(ua); const isTablet = /(iPad|Tablet|PlayBook)/.test(ua); // 当前不是移动端页面时才跳转 if((isMobile || isTablet) && !location.pathname.startsWith('/mobile')) { window.location.replace('/mobile/index.html'); // 用replace()避免产生历史记录 } } // 建议在<head>中尽早调用 deviceRedirect();
需要特别处理的新型设备特征:
HarmonyOS
标识 SM-F926U
等型号特征 MicroMessenger
,但可能需要特殊处理 // 综合判断示例(2025年推荐) function isRealMobile() { return window.matchMedia('(pointer:coarse)').matches || /Mobile|Android|iPhone|iPad|iPod/i.test(navigator.userAgent); }
:用JS实现移动端跳转就像给网站装上了"智能眼镜" 👓,能快速识别访客设备类型,2025年的今天,随着设备形态多样化,我们的识别逻辑也要持续升级!
(本文技术要点经测试验证,环境:Chrome 118 / Safari 17 / 鸿蒙4.0,2025年8月)
本文由 睢秋彤 于2025-08-02发表在【云服务器提供商】,文中图片由(睢秋彤)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vps.7tqx.com/wenda/518403.html
发表评论