总结:
1. display:none 让元素隐藏,不会显示在渲染树中,不会在dom文档占领位置,且子元素也不会展示,所以该元素的点击事件无用,使用display:none,会导致性能问题,因为会导致页面的重排
2. opacity:0 只是让内容不可见,透明度为0,在渲染树中,在dom文档中仍旧占领位置,子元素也不会展示,而且子元素不能通过设置opacity:1来展示,元素的点击事件可用
3. visibility:hidden 内容不可见,但是位置仍旧在渲染树中占领位置,但是点击事件无用,子元素设置 visibility: visible;可见,visibility 会导致页面重绘
示例:
- display:none可发现点击事件无用
<style>
.test {
width: 100px;
height: 100px;
background: red;
}
.test:nth-of-type(1) {
background: blue;
display: none;
}
</style>
<div class="test">
<div class="child">12</div>
</div>
<div class="test"></div>
<script>
document.getElementsByClassName('test')[0].onclick = function () {
alert(1)
}
</script>
2. opacity:0 点击事件可用
<style>
.test {
width: 100px;
height: 100px;
background: red;
}
.test:nth-of-type(1) {
background: blue;
opacity: 0;
}
</style>
<div class="test">
<div class="child">12</div>
</div>
<div class="test"></div>
<script>
document.getElementsByClassName('test')[0].onclick = function () {
alert(1)
}
</script>
3.visibility:hidden点击事件无用
.test {
width: 100px;
height: 100px;
background: red;
}
.test:nth-of-type(1) {
background: blue;
visibility: hidden;
}
<div class="test">
<div class="child">12</div>
</div>
<div class="test"></div>
<script>
document.getElementsByClassName('test')[0].onclick = function () {
alert(1)
}
</script>
但是子元素设置 visibility: visible; 可见
.child {
visibility: visible;
}