我正在尝试将一个覆盖div放置在另一个覆盖div上,以便将鼠标悬停在卡片div上时会在其上方显示覆盖div。但是在悬停时,我不知道为什么在显示叠加层div之前会有一些会产生波动效果的错误。
.overlay {
opacity: 0;
z-index: -2;
height: 290px;
width: 240px;
background: #000;
border-radius: 30px;
/*display: inline-block;*/
position: relative;
top: -310px;
transition: all .4s ease;
}
.card:hover + .overlay {
opacity: 1;
z-index: 1;
transition: all .4s ease;
}
<div class="card" style="background: #fff; height: 290px; width: 240px; border-radius: 30px; display: inline-block; margin:20px; box-shadow: 0 2px 6px rgba(112,112,112,0.2);"><img src="thumb.png" height="60%;"></div>
<div class="overlay"></div>
我在这里做什么错了?
答案 0 :(得分:5)
那是因为叠加层的z-index
通过悬停.card
而增加。但是现在您不再悬停.card
,而是悬停.overlay
,因此它消失了。
要解决此问题,您还应该添加.overlay:hover
样式:
.overlay {
opacity: 0;
z-index: -2;
height: 290px;
width: 240px;
background: #000;
border-radius: 30px;
/*display: inline-block;*/
position: relative;
top: -310px;
transition: all .4s ease;
}
.card:hover + .overlay, .overlay:hover {
opacity: 1;
z-index: 1;
transition: all .4s ease;
}
<div class="card" style="background: #fff; height: 290px; width: 240px; border-radius: 30px; display: inline-block; margin:20px; box-shadow: 0 2px 6px rgba(112,112,112,0.2);"><img src="thumb.png" height="60%;"></div>
<div class="overlay"></div>
答案 1 :(得分:1)
另一个想法是通过使用pointer-events: none;
来防止覆盖捕获事件(在这种情况下为悬停),以免丢失应用于卡的初始悬停:
.overlay {
opacity: 0;
z-index: -2;
height: 290px;
width: 240px;
background: #000;
border-radius: 30px;
pointer-events: none;
position: relative;
top: -310px;
transition: all .4s ease;
}
.card:hover+.overlay {
opacity: 1;
z-index: 1;
transition: all .4s ease;
}
.card {
background: red;
height: 290px;
width: 240px;
border-radius: 30px;
display: inline-block;
margin: 20px;
box-shadow: 0 2px 6px rgba(112, 112, 112, 0.2);
}
<div class="card"></div>
<div class="overlay"></div>
您还可以使用伪元素简化代码:
.card:before {
content:"";
position: absolute;
opacity: 0;
z-index: -2;
top:20px;
right:20px;
left:-20px;
bottom:-20px;
background: #000;
border-radius: 30px;
pointer-events: none;
transition: all .4s ease;
}
.card:hover::before {
opacity: 1;
z-index: 1;
transition: all .4s ease;
}
.card {
position:relative;
background: red;
height: 290px;
width: 240px;
border-radius: 30px;
display: inline-block;
margin: 20px;
box-shadow: 0 2px 6px rgba(112, 112, 112, 0.2);
}
<div class="card"></div>