
当面试官突然问你:“前端隐藏元素的方式有哪些?”你还是只知道
display: none吗? 其实,在前端开发的世界里,隐藏元素的方法非常多。每种方法都有自己的小技巧和使用场景,了解它们不仅能让你应对自如,还能让你的代码更优雅。
display: none;.hidden {
display: none;
}visibility: hidden;.hidden {
visibility: hidden;
}opacity: 0;pointer-events: none; 结合使用来禁用交互。.hidden {
opacity: 0;
pointer-events: none;
}position: absolute; 或 position: fixed; 结合 top: -9999px;.hidden {
position: absolute;
top: -9999px;
}clip 或 clip-pathclip 是旧属性,clip-path 更现代化,支持更多形状裁剪。.hidden {
clip: rect(0, 0, 0, 0);
clip-path: inset(50%);
}height: 0; 和 overflow: hidden;.hidden {
height: 0;
overflow: hidden;
}transform: scale(0); 或 transform: translateX(-100%);.hidden {
transform: scale(0);
}z-index: -1;.hidden {
z-index: -1;
}hiddendisplay: none;。<div hidden></div>aria-hidden="true"<div aria-hidden="true">隐藏内容</div>