【转】通过服务器端判断用户端信息,给页面html标签添加class name,简化浏览器兼容性hacks
用php实现通过userAgent信息来给页面html标签打上拟定好的class name。很简单,但对前端开发摆脱各种不知所云的hacks特殊符来说很有意义,同时也能更好的用一套代码兼容各种设备。
php实现方案的demo:http://www.zhaoyongming.com/lab/add-ua.php
php代码:
1 function useragent(){
2 $useragent = $_SERVER['HTTP_USER_AGENT'];
3 if(strstr($useragent, 'Win')){
4 $ua_system = 'ua-win';
5 }else if(strstr($useragent, 'Mac')){
6 $ua_system = 'ua-mac';
7 }else{
8 $ua_system = 'ua-other';
9 }
10 if(preg_match('|MSIE ([0-9])|', $useragent, $matched)){
11 $browser_version = $matched[1];
12 $ua_browser = 'ua-ie'.$browser_version;
13 }else if(preg_match('|Firefox/([0-9]+)|', $useragent, $matched)){
14 $browser_version = $matched[1];
15 $ua_browser = 'ua-ff'.$browser_version;
16 }else if(preg_match('|AppleWebKit|', $useragent)){
17 $ua_browser = 'ua-wk';
18 }else{
19 $ua_browser = 'ua-other';
20 }
21 return array("ua_system" => $ua_system, "ua_browser" => $ua_browser);
22 }
23 $ua = useragent();
24 ?>
在html标签上添加$ua返回的自定义的相对应的class name:
<html class="<?php echo $ua["ua_system"].' '.$ua["ua_browser"]; ?> ">
css代码hack示例:
.show{/*general style*/}
.ua-ie8 .show{/*IE8 hacks*/}
javascript代码hack示例(基于jQuery):
if($('.ua-ie8').find('.show')){
//todo ie8 special function
}
UserAgent 信息查阅: http://www.useragentstring.com/pages/useragentstring.php