网页中区分IE各版本

CSS Hack

直接在CSS文件中写CSS Hack是非常直观的区分方法。区分不同IE版本的hack代码为

#content{
background:red; /* 所有浏览器 */
background:orange9; /* 所有IE浏览器 */
*background:yellow; /* IE7和IE6 */
+background:green; /* IE7 */
_background:blue; /* IE6 */
}

还有一些hack不太实用,就不一一列举了。
CSS Hack的缺点是CSS文件无法通过W3C验证,代码阅读时会很奇怪。

条件注释CSS文件

条件注释是写在html里的只会被IE识别的代码,一般在<head>区域通过不同的条件注释导入不同的CSS,不同的IE浏览器会引用不同的CSS。下面的4段注释依次表示"在IE下使用"、“低于IE8时使用”、“IE7时使用”、“IE6时使用”:

<!--[if IE]>
<link rel="stylesheet" href="/ie-all.css" type="text/css" media="screen" />
<![endif]-->
<!--[if lt IE 8]>
<link rel="stylesheet" href="/ie.css" type="text/css" media="screen" />
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" href="/ie7.css" type="text/css" media="screen" />
<![endif]-->
<!--[if IE 6]>
<link rel="stylesheet" href="/ie6.css" type="text/css" media="screen" />
<![endif]-->

由于IE8下CSS问题较少,一般只需要为IE6、7写一点修正代码。如果需要,可以在ie.css里用CSS Hack对IE6/7进行差异处理。

<!--[if lt IE 8]>
<link rel="stylesheet" href="/ie.css" type="text/css" media="screen" />
<![endif]-->

条件注释CSS文件的缺点是会增加至少1次http请求,影响渲染速度,而且维护时不够方便。

条件注释<html>

条件注释<html>跟上面的方法原理一样,只不过这里是给<html>注释不同的class。

<!--[if lt IE 7 ]> <html class="ie6"> <![endif]-->
<!--[if IE 7 ]> <html class="ie7"> <![endif]-->
<!--[if IE 8 ]> <html class="ie8"> <![endif]-->
<!--[if IE 9 ]> <html class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html class=""> <!--<![endif]-->

这样在CSS中使用下面的代码即可区分版本

#content{background:red;}
.ie9 #content{background:orange;}
.ie8 #content{background:yellow;}
.ie7 #content{background:green;}
.ie6 #content{background:blue;}

你也可以增加诸如.ltie8这样的class来实现更方便的版本分组管理。这个方法不会增加http请求,而且不需要任何hack。

IE中的判断语句

上面写的<!--[if lte IE 6]>在正常的HTML中属于注释,不会被执行,但在IE中是一个判断语句,所以这些代码只有在IE中才会被识别并加载。

lte:就是Less than or equal to的简写,也就是小于或等于的意思。
lt :就是Less than的简写,也就是小于的意思。
gte:就是Greater than or equal to的简写,也就是大于或等于的意思。
gt :就是Greater than的简写,也就是大于的意思。
! : 就是不等于的意思,跟javascript里的不等于判断符相同
原文地址:https://www.cnblogs.com/sakura-panda/p/4193638.html