「前端小技巧」用CSS隐藏元素的几种方法
正文
用 CSS 隐藏元素有很多种方法,这里介绍 3 种常见的。
opacity: 0
特点是【看不见,占空间,摸得着】
- 元素隐藏
- 不改变布局
- 如果绑定了事件,点击该区域,是可以触发事件的
visibility: hidden
特点是【看不见,占空间,摸不着】
- 元素隐藏
- 不改变布局
- 如果绑定了事件,点击该区域,是无法触发事件的
display: none
特点是【看不见,不占空间,摸不着】
- 元素隐藏
- 改变布局
- 如果绑定了事件,点击该区域,是无法触发事件的
接下来,我们来编写代码验证一下。首先写入三个方块,对中间的橙色方块添加点击事件。代码及页面效果如下所示:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.box {width: 200px;height: 50px;}
.red {background-color: red;}
.orange {background-color: orange;}
.yellow {background-color: yellow;}
</style>
</head>
<body>
<div>
<div class='box red'></div>
<div class='box orange' id="btn"></div>
<div class='box yellow'></div>
</div>
<script type="text/javascript">
document.getElementById("btn").onclick = function() {
alert('触发点击操作 0.0');
}
</script>
</body>
</html>

image

image

image
opacity: 0
对中间橙色方块添加 opacity: 0 样式,代码及效果如下:
- 元素隐藏
- 不改变布局
- 如果绑定了事件,点击该区域,是可以触发事件的
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.box {width: 200px;height: 50px;}
.red {background-color: red;}
.orange {background-color: orange;}
.yellow {background-color: yellow;}
.opacity {opacity: 0}
</style>
</head>
<body>
<div>
<div class='box red'></div>
<div class='box orange opacity' id="btn"></div>
<div class='box yellow'></div>
</div>
<script type="text/javascript">
document.getElementById("btn").onclick = function() {
alert('触发点击操作 0.0');
}
</script>
</body>
</html>

image

image

image
visibility: hidden
对中间橙色方块添加 visibility: hidden 样式,代码及效果如下:
- 元素隐藏
- 不改变布局
- 如果绑定了事件,点击该区域,是无法触发事件的
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.box {width: 200px;height: 50px;}
.red {background-color: red;}
.orange {background-color: orange;}
.yellow {background-color: yellow;}
.visibility {visibility: hidden}
</style>
</head>
<body>
<div>
<div class='box red'></div>
<div class='box orange visibility' id="btn"></div>
<div class='box yellow'></div>
</div>
<script type="text/javascript">
document.getElementById("btn").onclick = function() {
alert('触发点击操作 0.0');
}
</script>
</body>
</html>

image

image

image
display: none
对中间橙色方块添加 display: none 样式,代码及效果如下:
- 元素隐藏
- 改变布局
- 如果绑定了事件,点击该区域,是无法触发事件的
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.box {width: 200px;height: 50px;}
.red {background-color: red;}
.orange {background-color: orange;}
.yellow {background-color: yellow;}
.display {display: none}
</style>
</head>
<body>
<div>
<div class='box red'></div>
<div class='box orange display' id="btn"></div>
<div class='box yellow'></div>
</div>
<script type="text/javascript">
document.getElementById("btn").onclick = function() {
alert('触发点击操作 0.0');
}
</script>
</body>
</html>

image

image