HTML5 Web中用javascript分辨移动设备(iPad、iPhone、Android)

发布时间:2015-08-28 12:52 | 人气数:1249

Javascript代码:

var deviceAgent = navigator.userAgent.toLowerCase();  
 var agentID = deviceAgent.match(/(iphone|ipod|ipad|android)/);  
 if(agentID.indexOf("iphone")>=0){  
  alert("iphone");  
 }  
 if(agentID.indexOf("ipod")>=0){  
  alert("ipod");  
 }  
 if(agentID.indexOf("ipad")>=0){  
  alert("ipad");  
 }  
 if(agentID.indexOf("android")>=0){  
  alert("android");  
 } 

HTML完整代码:

<!DOCTYPE html>  
<html>  
<head>  
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<style type="text/css">  
  html { height: 100% }  
  body { height: 100%; margin: 0px; padding: 0px }  
</style>  
<script type="text/javascript">  
  function initialize() {  
    var useragent = navigator.userAgent;  
    if (useragent.indexOf('iPhone') != -1) {  
        alert("iPhone");  
    } else if(useragent.indexOf('iPad') != -1 ) {  
        alert("iPad");  
    } else if(useragent.indexOf('Android') != -1 ) {  
        alert("Android");  
    } else {  
        alert("其他平台");  
    }  
  }  
</script>  
</head>  
<body onload="initialize()">  
</body>  
</html>

腾讯游戏推广中的一段代码,判断如果是移动设置跳转到HTML5网页:

<script type="text/javascript">
!function(){var a=navigator.userAgent;(-1!=a.indexOf("iPhone")||-1!=a.indexOf("iPad")||-1!=a.indexOf("iPod")||-1!=a.indexOf("Android"))&&(self.location="http://wefire.qq.com/act/a20150826kris/m/")}();
</script>

参考:http://wefire.qq.com/act/a20150826kris/pc/

关键词:js判断移动设备,CSS3, HTML5, JavaScript