Style opacity 属性
让 DIV 元素半透明:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>蜜蜂教程(mifengjc.com)</title>
<style>
#myDIV {
position: absolute;
width: 300px;
height: 150px;
background-color: lightblue;
border: 1px solid black;
}
#DIV2 {
position: relative;
top: 130px;
left: 30px;
width: 300px;
height: 150px;
background-color: coral;
border: 1px solid black;
}
</style>
</head>
<body>
<p>点击“尝试一下”按钮,透过蓝色的 DIV 元素看到底下的珊瑚色的 DIV 元素。</p>
<button onclick="myFunction()">尝试一下</button>
<div id="DIV2">
<h1>Voila!</h1>
</div>
<div id="myDIV">
</div>
<script>
function myFunction() {
document.getElementById("myDIV").style.opacity = "0.5";
}
</script>
</body>
</html>
定义和用法
opacity 属性设置或返回元素的不透明度。
元素的不透明度级别描述了透明度级别,当不透明度为 1 时表示完全不透明,当不透明度为 0.5 时表示半透明,当不透明度为 0 时表示完全透明。
浏览器支持
![]()
![]()
![]()
![]()
![]()
所有主流浏览器都支持 opacity 属性。
注意:IE8 及其之前的版本支持另一个可替代该属性的属性,即 filter 属性。
语法
返回 opacity 属性:
object.style.opacity
设置 opacity 属性:
object.style.opacity = "number|initial|inherit"
属性值
| 值 | 描述 |
|---|---|
| number | 规定不透明度。从 0.0 (完全透明)到 1.0(完全不透明)。 |
| initial | 设置该属性为它的默认值。请参阅 initial。 |
| inherit | 从父元素继承该属性。请参阅 inherit。 |
技术细节
| 默认值: | 1 |
|---|---|
| 返回值: | 字符串,表示元素的 opacity 属性。 |
| CSS 版本 | CSS3 |
相关文章
CSS 参考手册:opacity 属性
Style 对象
Style 对象