移动侦测 [英] Mobile detection

查看:14
本文介绍了移动侦测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to detect mobile devices using Javascript? Also, I researched that there are such an XML which contains user-agents that could help to identify the mobile handsets.

推荐答案

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

You probably have a normal site and you want to redirect to a mobile site if certain conditions are met, like the screen is very small, or the content is zoomed out to fit on a large "virtual" screen in a small physical space. So, why not check for those conditions instead of testing a zillion UA strings.

试试这样的:

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

For the UA to report the screen's physical pixel size, this tag must be present in the html page. *

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

现在,只需获取屏幕的大小并在需要时重定向.使用稍微延迟.**

Now, just get the size of the screen and redirect if needed. Use a slight delay. **

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

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

That's pretty much it. Since this page already has the viewport tag set up for mobile, you could also do the inverse, show mobile here and redirect to full site if screen is bigger.

我不确定为什么这个问题已经关闭;据我所知,它非常适合 SO 格式.投票重新开放.

I'm not sure why this question has been closed; as far as I can tell it fits the SO format pretty well. Voted to reopen.

* 用 javascript 插入它似乎不起作用(如果你想出办法,请有人纠正我).如果它不存在,手机将报告比实际屏幕大的虚拟屏幕尺寸.它似乎也不适用于 iframe,仅适用于顶级窗口(这是有道理的,因为 iframe 需要与外部窗口缩放相同的量,它们共享相同的视口).

** 一些移动浏览器会保留上次加载页面的视口大小,因此它们会在几毫秒内报告一个大的虚拟屏幕大小,直到他们注意到我猜的元标记.我找不到一个早期的事件来连接它,如果你有更好的方法,请发表评论.在我所有的测试中,50 毫秒的延迟都很好,100 应该是最安全的.

这篇关于移动侦测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆