JAVASCRIPT中怎么判斷訪客終端是電腦還是手機(jī),針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡(jiǎn)單易行的方法。
目前創(chuàng)新互聯(lián)已為千余家的企業(yè)提供了網(wǎng)站建設(shè)、域名、虛擬主機(jī)、綿陽服務(wù)器托管、企業(yè)網(wǎng)站設(shè)計(jì)、海勃灣網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長(zhǎng),共同發(fā)展。我們使用PHP的$_SERVER['HTTP_USER_AGENT']來獲取手機(jī)用戶瀏覽器的用戶代理,然后匹配已有的各種手機(jī)瀏覽器代理庫,如果含有匹配的關(guān)鍵字,則判斷為手機(jī)(移動(dòng)終端)用戶。
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;
}
上述代碼中函數(shù)is_mobile()來判斷用戶終端類型,將收集到的當(dāng)今各種手機(jī)的HTTP_USER_AGENT歸結(jié)到數(shù)組$mobile_agents中,并進(jìn)行匹配。使用時(shí)只需調(diào)用函數(shù)is_mobile()。如以下代碼表示,當(dāng)匹配用戶為手機(jī)訪問時(shí),頁面跳轉(zhuǎn)到網(wǎng)站手機(jī)版m.xuebuyuan.com。
if (is_mobile()) {
header('Location:http://m.xuebuyuan.com');
} else {
echo '請(qǐng)使用手機(jī)訪問.';
}
您也可以直接在前端頁面上加入一段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("請(qǐng)使用手機(jī)訪問.");
}
關(guān)于JAVASCRIPT中怎么判斷訪客終端是電腦還是手機(jī)問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識(shí)。