现在的位置: 我的问答 >js如何判断是否移动端

js如何判断是否移动端

2015-10-01 00:11 ⁄ 被浏览 6017

在手机站中,如何用js判断是否移动端,其实很简单。


方法一:用ontouchend判断是否支持触摸,支持触摸的设备大都都是移动端。


具体实现方法为:


if ( 'ontouchend' in document.body ) {

    // 移动端

}


这里为什么用ontouchend的原因是,ontouchend相对于ontouchstart、ontouchmove、ontouchcancel来说长度最短。


方法二:通过userAgent判断用户代理字符串中是否包含mobile关键字。


具体实现方法:


if ( /mobile/i.test(navigator.userAgent) ) {

    // 移动端

}