最近准备做一个手机端的网站。所以在网上找了几个判断是否是手机浏览器的js脚本,贴上来,分享下:
1.如何判断是否为移动终端 利用正则match,
匹配navigator.userAgent是否含有字符串AppleWebKit*****Mobile
安卓qq浏览器HD版 只有AppleWebKit
2手机语言版本的判断
使用navigator.browserLanguage 便可得出windows phone语言版本,
当然可恶的小小手机语言版本也有兼容性的差异,兼容Mozilla,以及AppleWebKit内核的浏览器访问其语言版本,它会列出 navigator.language
第一种、直接JS脚本:
代码如下 | 复制代码 |
try { var urlhash = window.location.hash; if (!urlhash.match("fromapp")) { if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iPad)/i))) { window.location = "http://www.111cn.net(更换成自己的WAP网站)"; } } } catch(err) {} |
第二种、引用(稍微长点):
代码如下 | 复制代码 |
function uaredirect(murl) { try { if (document.getElementById("bdmark") != null) { return; } var urlhash = window.location.hash; if (!urlhash.match("fromapp")) { if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iPad)/i))) { location.replace(murl); } } } catch(err) {} } |
第二种方式,页面调用:
上述的脚本保持到wap.js文件,然后在需要调用的页面引用下面2个JS调用文件。
代码如下 | 复制代码 |
<script src="wap.js" type="text/javascript"></script> <script type="text/javascript">uaredirect("http://www.111cn.net(更换成自己的WAP网站)");</script> |
参照 thinkphp 官网上的 php 代码修改的:
代码如下 | 复制代码 |
<script type="text/javascript"> var ua = navigator.userAgent, mobileAgents = ["240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi","android","anywhereyougo.com","applewebkit/525", "applewebkit/532","asus","audio","au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ","fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison", "inno","ipad","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mobi","mot-","moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo","samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony","spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit","tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte"]; |