Javascript侦测手机浏览器

243 阅读1分钟

一、navigator.userAgent

userAgent 属性是一个只读的字符串,声明了浏览器用于 HTTP 请求的用户代理头的值。 navigator 对象包含有关浏览器的信息,没有应用于 navigator 对象的公开标准,不过所有浏览器都支持该对象

navigator.appName 浏览器的名称 
navigator.language 浏览器使用的语言 
navigator.platform 浏览器使用的平台
navigator.userAgent 浏览器的user-agent信息
/Android|iPhone|iPad|iPod/i.test(navigator.platform)
/Mobi|Android|iPhone/i.test(navigator.userAgent)

二、window.screen,window.innerWidth

window.screen:用户设备的屏幕信息,该对象的width属性是屏幕宽度 window.innerWidth:浏览器窗口里面的网页可见部分的宽度

三、touch 事件

if("ontouchstart" in window)
if(document.hasOwnProperty("ontouchstart")//google的移动端模拟器上不适用**

四、window.orientation

判断设备横竖屏,只有移动设备才有这个属性,桌面设备会返回undefined, 注:iPhone 的 Safari 浏览器不支持该属性。

五、Window matchMedia()

if (window.matchMedia("(max-width: 700px)").matches)

addListener(function)添加一个新的监听器函数,该函数在媒体查询的结果发生变化时执行。 removeListener(function) 从媒体查询列表中删除之前添加的监听器。如果指定的监听器不在列表中,则不执行任何操作。