【问题标题】:How to detect whether the user is using mobile, tablet or desktop and redirect them?如何检测用户是在使用手机、平板电脑还是台式机并重定向它们?
【发布时间】:2016-02-20 04:02:39
【问题描述】:

首先我知道响应式网站不是。 1 但目前不幸的是,这不是一个选择!我也有非常好的 javascript 编码技能。

我需要检测用户使用的是台式机、平板电脑还是移动设备并重定向它们。

用户使用桌面 - 留在现场 (A)。 用户使用平板电脑 - 从 A 重定向到站点 B。 用户使用移动设备 - 从 A 重定向到站点 C。

如果我的屏幕宽度和 dpi 是否存在某些手机和平板电脑无论如何都会被捕获并重定向到桌面版本的可能性?

我现在有这个。

<script>
if (navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i)
) {
document.location = "B";
} else if (navigator.userAgent.match(/iPad/i)
) {
document.location = "C";
} else {
document.location = "A";
}
</script>

提前感谢您的帮助!

【问题讨论】:

标签: javascript redirect mobile


【解决方案1】:

您可以通过加载差异显示不同的内容来轻松做到这一点。 css,如果不想完全响应。我会使用 CSS 的 @media 标签,就像在 W3School 虚拟示例中一样

@media screen and (min-width: 480px) {
    body {
        background-color: lightgreen;
    }
}

现在,至于您的问题,通过为手机和平板电脑设置最大屏幕尺寸一个值,您通常不会遇到台式机/笔记本电脑的宽度问题。排除新 iPad Pro 后,99% 的平板电脑为 10 英寸及以下,而手机为 6 英寸及以下

就我个人而言,我不会按照你的方式使用 js,因为它在不需要的地方增加了复杂性。但是这个Blog post 也可能会有所帮助。

【讨论】:

    【解决方案2】:

    您的解决方案看起来不错,只需添加一个屏幕宽度检查,ipad 或标签为 970 像素,移动设备(智能手机)为 768 像素,桌面版大于 970 像素。

    您似乎无法使用媒体查询,因为您想根据设备进行重定向,否则媒体查询是进行响应式设计的最佳方式。

    你也可以看看下面的链接。

    https://css-tricks.com/snippets/javascript/redirect-mobile-devices/

    【讨论】:

      【解决方案3】:

      如果有人感兴趣,我想出了这个解决方案。到目前为止效果很好。不知道将来是否可以安全使用 - 可能不是。但是,如果您没有其他解决方案或无法创建一个响应式网站或类似的东西,您可以适当地使用它......

      我使用最常用的设备。

      if (/iP(hone|od)|android.+mobile|BlackBerry|IEMobile/i.test(navigator.userAgent)) {
          window.location.replace("http://mobile");
      } else if (/(tablet|ipad|playbook|silk)|(android(?!.*mobile))/i.test(navigator.userAgent)) {
          window.location.replace("http://tablet.website.com");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-10
        • 2012-07-05
        • 1970-01-01
        • 1970-01-01
        • 2015-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多