在日常开发中,我们通常会选择使用 javascript 切换类来控制它们的状态样式,比如 .open
、.closed
,.show
、.hide
。
在本篇文章中,我们将探索以下几个方面内容:
- 在元素没有子元素的情况下,使用
:empty
伪类来隐藏元素 - 将
:empty
与:has()
和:not()
结合使用,可以处理更多情况 - 梳理隐藏元素的常见方法
1.隐藏一个空元素
:empty
伪类可以匹配任何没有子元素的元素。当前已经得到所有主流浏览器的支持。如果该元素是一个空元素,我们可以结合 display
属性使用来隐藏元素。
示例:
<style>
.box {
display: flex;
width: 80%;
height: 80px;
background-color: #ccc;
border-radius: 5px;
margin: 0 auto 10px;
justify-content: center;
align-items: center;
}
.box:empty {
display: none;
}
</style>
<div class="box">1</div>
<div class="box"></div>
<div class="box">3</div>
<div class="box">4</div>
效果如下:
2.和 :has() 和 :not() 结合使用
和 :has() 和 :not() 结合使用时,我们可以在更多复杂场景中使用,比如查找子元素有空元素的元素、隐藏一个不包含某个子元素的父元素等。
2.1.查找子元素为空的父元素
下面的例子是每个 .box
盒子都有一个 span
元素,其中 3 个 span
元素是有文本节点的,一个没有。通过和 :has()
结合使用,我们可以先找到子元素为空的原生 span:empty
, 然后通过 .box:has(span:empty)
判断 .box
下是否有子元素 span
为空的父元素,并隐藏它。
<style>
.box {
display: flex;
width: 80%;
height: 80px;
background-color: #ccc;
border-radius: 5px;
margin: 0 auto 10px;
justify-content: center;
align-items: center;
}
.box:not(span:has(:empty)) {
display: none;
}
</style>
<div class="box"><span>1</span></div>
<div class="box"><span>2</span></div>
<div class="box"><span></span></div>
<div class="box"><span>4</span></div>
效果如下:
2.2.查找不包含某个子元素的父元素
下面的示例是首先查找 .box
元素下有 .text
子元素的父元素,然后使用 .box:not()
进行取反操作,结合 display
属性对元素执行隐藏。
<style>
.box {
display: flex;
width: 80%;
height: 80px;
background-color: #ccc;
border-radius: 5px;
margin: 0 auto 10px;
justify-content: center;
align-items: center;
}
.box:not(.box:has(.text)) {
display: none;
}
</style>
<div class="box"><span class="text">1</span></div>
<div class="box"><span>2</span></div>
<div class="box"><span>3</span></div>
<div class="box"><span class="text">4</span></div>
3.隐藏元素的常见方法
方法一:display: none
此方法使用的最多,该方法会使 DOM 隐藏,触发 Reflow 和 Repaint。
方法二:visiblity: hidden
此方法 DOM 结构无变化,隐藏后仍占据空间,仅会触发 Repaint。 结构保留,占据空间,仅触发重绘,不会触发事件(无法选中)。
方法三:opacity: 0
此方法 DOM 结构无变化,隐藏后仍占据空间。
方法四:content-visibility: hidden
它能让用户代理跳过元素的呈现工作(包括布局和绘制),直到需要时才进行,这使得初始页面加载速度大大加快。
方法五:position + left + top
它能让元素脱离文档流,不占用空间,并且通过设置 left 或者 top 属性负值,可以将元素定位到屏幕之外。
方法六:transform: translate(-999px)
它能让元素偏移出视图窗口,空间会占据,但元素实际不在视窗内所以无法交互。
方法七:font-size: 0
通过设置字体大小为0,将行内元素内容隐藏,但是实际空间还在。
方法八:width:0;height:0;overflow:hidden
通过设置元素宽高为0和设置 overflow: hidden
来实现元素隐藏,不占空间。
方法九:hidden property
通过设置 html 标签的 hidden 来实现元素隐藏。
方法十:clip-path
clip-path属性会创建一个裁剪区域,用于确定元素的哪些部分可见。使用clip-path: circle(0)可以达到将元素隐藏的效果。
方法十一:filter: blur(0)
将一个元素的模糊度设置为0, 从而使这个元素“消失”在页面中。
4.最后
随着浏览器对 :empty
、:has()
、:not()
等伪类和方法的支持越来越好,之前使用 js 来实现的功能,完全可以使用 CSS 来替换,替换后有着更好的性能和用户体验。本文最后梳理了隐藏元素的常见方法,如果你有其他方法,欢迎在文章下方留言告诉,欢迎一起讨论和交流。