如何在移动端检测后触发window.alert提示用户切换至横屏模式?
解决移动设备检测后提示横屏的问题
嘿,刚接触JavaScript完全不用慌,你的思路已经很对啦!这段检测移动设备的代码没问题,咱们只需要加一点点逻辑,就能实现检测到移动设备时弹出提示的效果。
方法一:直接修改检测函数
你可以把弹窗逻辑直接写到detectmob函数里,这样调用函数的时候自动判断并弹出提示:
<head> <script language="JavaScript" type="text/javascript"> function detectmob() { // 先判断是否是移动设备 const isMobile = navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i); if (isMobile) { // 如果是移动设备,弹出横屏提示 window.alert('请切换至横屏模式,获得更优浏览体验哦!'); return true; } else { return false; } } </script> </head> <body onload="detectmob()"> <!-- 你的页面内容 --> </body>
方法二:保留原函数,在调用时判断
如果你想保持原检测函数的独立性,也可以在onload事件里直接判断返回值:
<head> <script language="JavaScript" type="text/javascript"> function detectmob() { if( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) ){ return true; } else { return false; } } </script> </head> <body onload="if(detectmob()) window.alert('请切换至横屏模式!')"> <!-- 你的页面内容 --> </body>
小提示
- 用
navigator.userAgent检测设备不是100%精准,但对于新手入门来说完全够用啦; - 你可以根据需求调整弹窗里的提示文字,让它更贴合你的网站场景~
内容的提问来源于stack exchange,提问作者EriComic
相关产品推荐
相关产品推荐

