詳談IE條件注釋
概述
如果你厭煩了為低版本IE寫又臭又長的hack,IE條件注釋將是比較優美的解決方案。當然條件注釋的功能不僅僅是以上那些功能,除了規避寫出噁心的hack,它還可以針對不同的IE版本(IE5.5-9,IE10不支援條件注釋)做出不同的相應,比如針對不同IE載入不同的樣式,或者指令碼等等,更多的功能等待我們的發掘和運用。
條件注釋簡介
IE中的條件注釋(Conditional comments)對IE的版本和IE非IE有優秀的區分能力,是WEB設計中常用的hack方法。
條件注釋只能用於IE5以上,IE10以上不支援。
如果你安裝了多個IE,條件注釋將會以最高版本的IE為標準。
條件注釋的基本結構和HTML的注釋(<!– –>)是一樣的。因此IE以外的瀏覽器將會把它們看作是普通的注釋而完全忽略它們。
IE將會根據if條件來判斷是否如解析普通的頁面內容一樣解析條件注釋裡的內容。
條件注釋文法
| 項目 |
範例 |
說明 |
| ! |
[if !IE] |
The NOT operator. This is placed immediately in front of the feature, operator, or subexpression to reverse the Boolean meaning of the expression.
NOT運算子。這是擺立即在前面的功能,操作員,或子運算式扭轉布林運算式的意義。 |
| lt |
[if lt IE 5.5] |
The less-than operator. Returns true if the first argument is less than the second argument.
小於運算子。如果第一個參數小於第二個參數,則返回true。 |
| lte |
[if lte IE 6] |
The less-than or equal operator. Returns true if the first argument is less than or equal to the second argument.
小於或等於運算。如果第一個參數是小於或等於第二個參數,則返回true。 |
| gt |
[if gt IE 5] |
The greater-than operator. Returns true if the first argument is greater than the second argument.
大於運算子。如果第一個參數大於第二個參數,則返回true。 |
| gte |
[if gte IE 7] |
The greater-than or equal operator. Returns true if the first argument is greater than or equal to the second argument.
大於或等於運算。如果第一個參數是大於或等於第二個參數,則返回true。 |
| ( ) |
[if !(IE 7)] |
Subexpression operators. Used in conjunction with boolean operators to create more complex expressions.
子運算式電訊廠商。在與布林運算子用於建立更複雜的運算式。 |
| & |
[if (gt IE 5)&(lt IE 7)] |
The AND operator. Returns true if all subexpressions evaluate to true
AND運算子。如果所有的子運算式計算結果為true,返回true |
| | |
[if (IE 6)|(IE 7)] |
The OR operator. Returns true if any of the subexpressions evaluates to true.
OR運算子。返回true,如果子運算式計算結果為true。 |
條件注釋使用方法樣本
<!–[if IE 5]>僅IE5.5可見<![endif]–>
<!–[if gt IE 5.5]>僅IE 5.5以上可見<![endif]–>
<!–[if lt IE 5.5]>僅IE 5.5以下可見<![endif]–>
<!–[if gte IE 5.5]>IE 5.5及以上可見<![endif]–>
<!–[if lte IE 5.5]>IE 5.5及以下可見<![endif]–>
<!–[if !IE 5.5]>非IE 5.5的IE可見<![endif]–>
條件注釋使用案例
特別提示:
1、有人會試圖使用<!--[if !IE]>來定義非IE瀏覽器下的狀況,但注意:條件注釋只有在IE瀏覽器下才能執行,這個代碼在非IE瀏覽下被當做注釋視而不見。
2、我們通常用IE條件注釋根據瀏覽器不同載入不同css,從而解決樣式相容性問題的。其實它可以做的更多。它可以保護任何代碼塊——HTML代碼塊、JavaScript代碼塊、伺服器端代碼……看看下面的代碼。
代碼如下:
<!--[if IE]>
<script type="text/javascript">
alert("你使用的是IE瀏覽器!");
</script>
<![endif]-->