说到更改背景色的透明度,可能大家有很多写法;例如:opacity,rgba()和IE6~IE9专用的filter专属滤镜属性。没错上面的这些属性都可以改变背景的透明度,但是它们也会改变子元素的透明度。让我们逐个分析这些属性的特性;
以上测试效果可知,背景的透明度发生改变,但其子元素的透明度没有改变。可惜该属性不支持IE6~IE8浏览器。
1.opacity属性—改变子元素透明度(该属性只支持IE9+,谷歌,火狐等标准浏览器)。并且没有解决的办法;
实例代码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
html,body {
width:100%;
height:100%;
font-family: "微软雅黑";
}
.demo {
width:100px;
height:100px;
background: #000;
opacity: .4;
}
.text {
font-size: 2em;
color:#f00;
position: absolute;
}
</style>
</head>
<body>
<div class="demo">
<p class="text">测试透明度</p>
</div>
</body>
</html>
在一些标准浏览器中测试(谷歌,火狐,QQ等浏览器)发现子元素的透明度跟着背景的透明度一起改变了,效果如下:
以上我还没有什么解决办法,自认为这种方式没有解决方法。如果哪位大神知道,请告知。
2.rgba写法。rgba它不是一种新的属性,它是属性值。一般作用与background-color属性。该属性同上述属性一样,只支持IE9+等标准浏览器。它不会改变子元素的透明度。
实例代码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
html,body {
width:100%;
height:100%;
font-family: "微软雅黑";
}
.demo {
width:100px;
height:100px;
background: rgba(0,0,0,.4);
}
.text {
font-size: 2em;
color:#f00;
position: absolute;
}
</style>
</head>
<body>
<div class="demo">
<p class="text">测试透明度</p>
</div>
</body>
</html>
以上测试效果可知,背景的透明度发生改变,但其子元素的透明度没有改变。可惜该属性不支持IE6~IE8浏览器。
3.filter属性可以说是IE的专有属性—只对IE浏览器有效。
实例代码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
html,body {
width:100%;
height:100%;
font-family: "微软雅黑";
}
.demo {
width:100px;
height:100px;
background: rgb(0,0,0);
filter:Alpha(opacity=40);
}
.text {
font-size: 2em;
color:#f00;
}
</style>
</head>
<body>
<div class="demo">
<p class="text">测试透明度</p>
</div>
</body></html>
该代码片段就不贴上效果图,想确认的看客可以自行拷贝运行
以上测试效果知道该属性也会改变子元素,但是只要给子元素设置position定位属性。子元素的透明度就不会被更改。
我上网了解过,有些人说在父元素上要设置position:static属性和*zoom:1才能有效,但是我在没有添加该属性的前提,一样有效。可惜电脑上没有IE6浏览器,无法测试这种方法是不是为了兼容IE6浏览器。
4.兼容性模式—代码如下
实例代码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
html,body {
width:100%;
height:100%;
font-family: "微软雅黑";
}
.demo {
width:100px;
height:100px;
background: #000;
background: rgba(0,0,0,.4);
filter:Alpha(opacity=40);
*zoom:1; /*激活haslyout*/
position:static;
}
.text {
font-size: 2em;
color:#f00;
position: absolute;
}
</style>
</head>
<body>
<div class="demo">
<p class="text">测试透明度</p>
</div>
</body>
</html>
4.怪招模式—代码如下
就是用2个同辈div标签,背景元素的下面,子元素在背景元素的上面。这样就完全兼容了。
实例代码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
html,body {
width:100%;
height:100%;
font-family: "微软雅黑";
}
.demo {
width:100px;
height:100px;
position: relative;
}
.text1 {
width:100px;
height:100px;
background: #000;
opacity: .4;
filter:Alpha(opacity=40);
color:#f00;
position: absolute;
}
.text2 {
width:100px;
height:100px;
position: absolute;
z-index:99999;
color:#f00;
font-size: 2em;
}
</style>
</head>
<body>
<div class="demo">
<p class="text1"></p>
<p class="text2">测试透明度</p>
</div>
</body>
</html>