您好,登錄后才能下訂單哦!
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也是通過獲取瀏覽器的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中怎么判斷訪客終端是電腦還是手機問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。