JAVASCRIPT中怎么判断访客终端是电脑还是手机-创新互联
JAVASCRIPT中怎么判断访客终端是电脑还是手机,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
目前创新互联已为千余家的企业提供了网站建设、域名、虚拟主机、绵阳服务器托管、企业网站设计、海勃湾网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。我们使用PHP的$_SERVER['HTTP_USER_AGENT']来获取手机用户浏览器的用户代理,然后匹配已有的各种手机浏览器代理库,如果含有匹配的关键字,则判断为手机(移动终端)用户。
function is_mobile() {
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$mobile_agents = array("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","iphone","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");
$is_mobile = false;
foreach ($mobile_agents as $device) {
if (stristr($user_agent, $device)) {
$is_mobile = true;
break;
}
}
return $is_mobile;
}
上述代码中函数is_mobile()来判断用户终端类型,将收集到的当今各种手机的HTTP_USER_AGENT归结到数组$mobile_agents中,并进行匹配。使用时只需调用函数is_mobile()。如以下代码表示,当匹配用户为手机访问时,页面跳转到网站手机版m.xuebuyuan.com。
if (is_mobile()) {
header('Location:http://m.xuebuyuan.com');
} else {
echo '请使用手机访问.';
}
Javascript版
您也可以直接在前端页面上加入一段Javascript脚本来判断用户的终端类型。Javascript也是通过获取浏览器的user-agent信息,然后匹配已有的user-agent信息库。
if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|
WebOS|Symbian|Windows Phone|Phone)/i))) {
location.replace("http://m.xuebuyuan.com")
}else{
document.write("请使用手机访问.");
}
关于JAVASCRIPT中怎么判断访客终端是电脑还是手机问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。
分享题目:JAVASCRIPT中怎么判断访客终端是电脑还是手机-创新互联
文章转载:http://ybzwz.com/article/ddcpjd.html