HTML5:使用javascript检测您是使用手机还是PC? [英] HTML5: Detecting if you're on mobile or pc with javascript?

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

问题描述

我可以用什么javascript代码来检测用户是否在HTML5的移动浏览器或pc / mac浏览器中? 几年前我正在研究这个问题。简而言之,您不能以100%的可靠性来做到这一点。似乎有两种常用的方法来提供最佳猜测:

1。用户代理检测
这是您检查客户端声称​​ 的地方。
例如


$ b $

if(/ Android | webOS | iPhone | iPad | iPod | BlackBerry | IEMobile | Opera Mini / i.test(导航器。 userAgent)){
//移动..
}

不是完美,因为我相信这个属性很容易被意外或其他方式改变。此外,这份名单在2年/ 2周/ 2天内仍然是准确的!!

2。使用客户端功能
您可以想象,更实用的方法 - 可以满足客户已知的物理功能。例如

  if(screen.width< = 480){
//移动..
}

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



如果有人有更好的想法可以在桌面和设备之间进行有效识别,请评论! :)

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

解决方案

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. 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..
}

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. 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天全站免登陆