有IE就有hack,看看IE9的css hack,IE8的css hack;上次同事說一個頁面IE10下有問題,IE9下測試了一下,也有同樣的問題。悲劇了趕緊找IE10的hack。
google上翻到的IE10 CSS Hacks 還算比較實用的。記錄一下以備后用。
一、特性檢測:@cc_on
我們可以用IE私有的條件編譯(conditional compilation)結合條件注釋來提供針對ie10的Hack:該腳本里面的IE排除條件注釋,以確保IE6-9不承認它,然后它功能檢測到了名為@ cc_on。
1
2
3
4
5
|
<!--[if !IE]><!--><script>
if (/*@cc_on!@*/false) {
document.documentElement.className+=' ie10';
}
</script><!--<![endif]-->
|
請注意/*@cc_on ! @*/中間的這個感嘆號。
這樣就可以在ie10中給html元素添加一個class=”ie10″,然后針對ie10的樣式可以卸載這個這個選擇器下:
1
2
3
|
.ie10 .example {
/* IE10-only styles go here */
}
|
這是ie10標準模式下的截圖:
這是ie10,IE8模式下的截圖:
考錄到兼容以后的IE版本,比如IE11,js代碼可以改一下:
1
2
3
|
if (/*@cc_on!@*/false) {
document.documentElement.className+=' ie' + document.documentMode;
}
|
關于document.documentMode可以查看IE的documentMode屬性(IE8+新增)。
可能是想多了,實事上經測試預覽版的IE11已經不支持@ cc_on語句,不知道正式版會不會支持。不過這樣區分IE11倒是一件好事。這樣修改代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>無標題文檔</title>
<!--[if !IE]><!-->
<script>
// 針對IE10
if (/*@cc_on!@*/false) {
document.documentElement.className += ' ie' + document.documentMode;
}
// 針對IE11及非IE瀏覽器,
// 因為IE11下document.documentMode為11,所以html標簽上會加ie11樣式類;
// 而非IE瀏覽器的document.documentMode為undefined,所以html標簽上會加ieundefined樣式類。
if (/*@cc_on!@*/true) {
document.documentElement.className += ' ie' + document.documentMode;
}
</script>
<!--<![endif]-->
<style type="text/css">
.ie10 .testclass {
color: red
}
.ie11 .testclass {
color: blue
}
.ieundefined .testclass {
color: green
}
</style>
</head>
<body>
<div class="testclass">
test text!
</div>
</body>
</html>
|
其中:
1
2
3
|
if (/*@cc_on!@*/true) {
document.documentElement.className += ' ie' + document.documentMode;
}
|
以上代碼是針對IE11及非IE瀏覽器,因為:
- IE11下document.documentMode為11,所以html標簽上會加ie11樣式類;
- 而非IE瀏覽器的document.documentMode為undefined,所以html標簽上會加ieundefined樣式類。
這樣把IE11也區分出來了,IE11預覽版下的截圖:
。
呵呵,純屬YY,IE11正式版還不知道什么樣子,而且在實際的項目中隨著IE的逐漸標準化,IE11和IE10可能很少用不到css hack。
二、@media -ms-high-contrast 方法
IE10支持媒體查詢,然后也支持-ms-high-contrast這個屬性,所以,我們可以用它來Hack IE10:
1
2
3
|
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
/* IE10-specific styles go here */
}
|
這種寫法可以適配到高對比度和默認模式。所以可以覆蓋到所有ie10的模式了。這種方式在預覽版的IE11中也生效。
當然,方法二也可以和方法一一起用:
1
2
3
|
if (window.matchMedia("screen and (-ms-high-contrast: active), (-ms-high-contrast: none)").matches) {
document.documentElement.className += "ie10";
}
|
三、@media 0 方法
這個方法不是太完美,因為IE9和預覽版的IE11也支持media和\0的hack。
1
2
3
|
@media screen and (min-width:0\0) {
/* IE9 , IE10 ,IE11 rule sets go here */
}
|
總之,隨著IE的逐漸標準化,IE11和IE10可能很少用不到css hack,不看也罷,呵呵。