移动检测[关闭]

2024-01-06

有没有办法使用 Javascript 检测移动设备?另外,我研究了这样一个 XML,其中包含可以帮助识别移动手机的用户代理。


您可能有一个普通网站,并且如果满足某些条件(例如屏幕非常小,或者内容被缩小以适应较小的物理空间中的大“虚拟”屏幕),您希望重定向到移动网站。那么,为什么不检查这些条件而不是测试无数的 UA 字符串。

尝试这样的事情:

为了让 UA 报告屏幕的物理像素大小,该标签必须出现在 html 页面中。 *

<meta name="viewport" 
      content="width=device-width, initial-scale=1, maximum-scale=1" />

现在,只需获取屏幕的大小并根据需要进行重定向。使用轻微的延迟。 **

setTimeout(function(){
  if ((screen.width < 480) || (screen.height < 480)) {
    location.replace('/mobile/');
  }
}, 100);

差不多就这样了。由于此页面已经为移动设备设置了视口标签,因此您也可以执行相反的操作,在此处显示移动设备并重定向到完整网站(如果屏幕更大)。

编辑:我不确定为什么这个问题已被关闭;据我所知它非常适合 SO 格式。投票决定重新开放。

* Inserting it with javascript doesn't seem to work (someone please correct me if you figure out a way). If it isn't present, the phone will report a virtual screen size that is larger than the actual screen. It also doesn't seem to work in iframes, only top level windows (which makes sense because iframes will need to be scaled the same amount as the outer window, they share the same viewport).

** Some mobile browsers keep the viewport size from the last loaded page, so they report a large virtual screen size for a few milliseconds, until they notice the meta tag I guess. I couldn't find an early event to hook this into, please comment if you have a better way of doing this. 50 ms delay worked fine in all my tests, 100 should be mostly safe.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

移动检测[关闭] 的相关文章

随机推荐