一、CSS 隐藏盒子的方式
说到 CSS 隐藏盒子的方式,除了 display:none; visibility: hidden; opacity: 0;这三种,你还知道哪些呢?话不多说,先上 demo ~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.red,
.pink {
width: 100px;
height: 100px;
}
.red {
/* ◆法1 */
display: none;
/* ◆法2 */
/* visibility: hidden; */
/* ◆法3 */
/* opacity: 0; */
/* ◆法4 */
/* transform: translate(-9999px); */
/* ◆法5 */
/* transform: scale(0); */
/* ◆法6 */
/* margin-top: -9999px; */
/* ◆法7 */
/* position: absolute;
left: -9999px; */
/* ◆法8 */
/* position: relative;
left: -9999px; */
/* ◆法9 */
/* position: absolute;
z-index: -9999; */
/* ◆法10 */
/* position: fixed;
z-index: -9999; */
background-color: red;
}
.pink {
background-color: pink;
}
</style>
</head>
<body>
<div class="red" @click="boxClickHandler">
<p>我是被隐藏盒子的子元素</p>
</div>
<div class="pink"></div>
</body>
<script>
// 注册点击事件
document.querySelector('.red').onclick = () => {
console.log('我被点击了!');
}
</script>
</html>
二、CSS 隐藏元素的方式的区别
- display 为 none
- 不占位置
- 会引起重排和重绘
- visibility 为 hidden
- 依然占位置
- 会引起重绘
- 子元素设置
visibility为visible,即可见
- opacity 为 0
- 依然占位置
- 会引起重绘
自身绑定点击事件有效
- transform: translate(负值)
- 依然占位置
- 会引起重绘
- transform: scale(0)
- 依然占位置
- 会引起重绘
- margin 负值
- 不占位置
- 会引起重排和重绘
- position 为 absolute 时:边偏移负值
- 不占位置
- 会引起重排和重绘
- position 为 reactive 时:边偏移负值
- 依然占位置
- 会引起重排和重绘
- position 为 absolute 时:z-index 为负值
- 不占位置
- 会引起重排和重绘
- position 为 fixed 时:z-index 为负值
- 不占位置
- 会引起重排和重绘