IE8下兼容rgba顏色的半透明背景
這樣的標題在百度和google搜索下很多篇文章,講解IE8下兼容rgba的。
這些文章全部都是使用IE下的filter來使元素透明,但是這個里面會有bug。
它們的如下:
background: rgba(0,0,0,.5); /*支持rgba的瀏覽器*/
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#7f000000,endColorstr=#7f000000);
IE filter 的bug
簡答評論下這個代碼的問題,首先這代碼在IE9+上就會有顏色疊加的bug,fliterIE9+也同樣支持的
其次IE8上確實是可以運行,但是這個元素對css的:hover,js的click事件(其他事件沒有測試)支持將變得怪異,這個bug我的理解是IE對使用了filter的對象將會降低它的層次,就想是使用的z-index的感覺,只是視覺上沒有變化,看 例子
注意,在例子中只有有文字的地方才能觸發hover事件和點擊事件,沒有文字的地方點擊事件就直接穿這個div點擊到了下面一層的div了。這里才是重點。
我的解決方式
代碼先行
// css
.a1{
margin: 10px auto 0;
width: 200px;
height: 200px;
position: relative;
overflow: hidden;
background: lightblue
}
.a2{
width: 130px;
height: 160px;
margin-left: 20px;
margin-top: 20px;
background: pink
}
.a3{
position: absolute;
right: 0;
top: 50%;
margin: 20px;
height: 120px;
width: 110px;
margin-top: -60px;
background: no-repeat, rgba(128,128,128,.5);
color: black;
font-size: 12px;
z-index: 2
}
.a3 > .background-mask{
filter: progid:DXImageTransform.Microsoft.gradient(startcolorstr=#7F808080,endcolorstr=#7F808080);
zoom: 1;
}
.a3:hover{
color: white;
}
//html
<div class="a1">
<div onclick="a2(this)" class="a2"></div>
<div onclick="a3(this)" class="a3">
我是a3,我用IE的filter屬性的,我有hover看我的顏色,我還有click事件,分別點擊文字和我的空白的地方
<!--[if IE 8]><div class="background-mask"></div><![endif]-->
</div>
</div>
可以看 例子 方便點
關鍵的地方是background: no-repeat, rgba(128,128,128,.5);
用background的多個屬性讓background在IE8上永不生效,然后IE8用<!--[if IE 8]><div class="background-mask"></div><![endif]-->
來生成背景
對於文字會被filter影響的問題,可以把文字和filter分開放,然后用z-index把文字內容放在filter上層,這樣filter就不會把文字內容影響到了。
這次主要是說明了下ie8上兼容透明背景的使用,還是一個觀點問題,背景就應該在內容的下方,這樣就不會出怪異問題。使用了filter屬性的元素注定只有當背景。