HTML5:使用 javascript 检测您是在移动设备上还是在 PC 上? [英] HTML5: Detecting if you're on mobile or pc with javascript?

查看:15
本文介绍了HTML5:使用 javascript 检测您是在移动设备上还是在 PC 上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用哪些 javascript 代码来检测用户是否使用 HTML5 中的移动或 pc/mac 浏览器?

What javascript code can I use to detect if users are on a mobile or pc/mac browser in HTML5?

推荐答案

几年前我正在研究这个.简而言之,您不能以 100% 的可靠性做到这一点.似乎有两种常用的方法可以提供最佳猜测":

I was looking into this a few years back. In short, you can't do this with 100% reliability. There seem to be 2 approaches commonly used to provide a 'best-guess':

1.用户代理检测在这里您可以检查客户声称是什么.例如

1. User Agent Detection This is where you check what the client is claiming to be. e.g.

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
    // is mobile..
}

它并不完美,因为我相信这个属性很容易被意外或以其他方式改变.此外,这份清单在 2 年/2 周/2 天后仍然准确的可能性很小!

It's not perfect, since I believe it is fairly easy for this property to be altered accidentally or otherwise. Plus it is highly unlikely that this list will still be accurate in 2 years' / 2 weeks' / 2 days' time!

2.使用客户端功能可以想象,一种更务实的方法 - 允许您迎合客户已知的身体能力.例如

2. Using Client Capabilities As you can imagine, a more pragmatic approach - allows you to cater to the known physical capability of the client. e.g.

if( screen.width <= 480 ) {     
    // is mobile.. 
}

然而,这也不理想,因为现代设备中越来越高的像素密度会给您一个误导性的结果:看起来您拥有比实际更多的空间".此外,不同的浏览器可能会通过不同的方式公开其功能.

However this is not ideal either, since higher and higher pixel densities in modern devices give you a misleading result: appearing that you have more 'room' than you actually do. Plus different browsers may expose their capabilities through different means.

如果有人有更好的想法来区分桌面和设备,请发表评论!:)

If anyone has any better ideas to robustly discern between desktop and device, please comment! :)

这篇关于HTML5:使用 javascript 检测您是在移动设备上还是在 PC 上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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