CSS3 : 悬停时淡入,悬停消失时淡出

CSS3 : Fade in on hover and Fade out when hover is gone

我有一个div。当我悬停在它上面时,它应该使用 fadeIn 效果出现,当我移除鼠标时它应该使用 fadeOut 效果消失。

我试过下面的代码。

.main_div{
width:100px;
height:100px;
border:thin black solid;
position:relative;

}

.main_div .overlay_div{
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
width:100%;
height:100%;
display:none;
background:rgba(0,0,0,0.5);
opacity: 0;
transition: opacity;
transition-timing-function: ease-out;
transition-duration: 100ms;
transition-delay: 1s;
    
-ms-transition: opacity;
-ms-transition-timing-function: ease-out;
-ms-transition-duration: 100ms;
-ms-transition-delay: 1s; 
    
-moz-transition: opacity;
-moz-transition-timing-function: ease-out;
-moz-transition-duration: 100ms;
-moz-transition-delay: 1s; 
    
-webkit-transition: opacity;
-webkit-transition-timing-function: ease-out;
-webkit-transition-duration: 100ms;
-webkit-transition-delay: 1s;    


}

.main_div:hover .overlay_div{
display:block;

opacity: 1;

/* Fade in */
transition: opacity;
transition-timing-function: ease-out;
transition-duration: 100ms;

-ms-transition:opacity;
-ms-transition-timing-function: ease-out;
-ms-transition-duration: 100ms;

-moz-transition:opacity;
-moz-transition-timing-function: ease-out;
-moz-transition-duration: 100ms;

-webkit-transition: opacity;
-webkit-transition-timing-function: ease-out;
-webkit-transition-duration: 100ms;

}
<div class="main_div">
  <div class="overlay_div">
    some text
  </div>
</div>

任何帮助都会很棒。

谢谢。

CSS 过渡效果不适用于 display:block/none; 您可以使用 visibility/opacity 属性来实现这种效果。

检查这个例子,你可以手动添加 transition-delay 属性 如果你真的想要它添加。

.main_div {
  width: 100px;
  height: 100px;
  border: thin black solid;
  position: relative;
}

.main_div .overlay_div {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  visibility: hidden;
  opacity: 0;
  transition: all 1s ease-out;
}

.main_div:hover .overlay_div {
  visibility: visible;
  opacity: 1;
  transition: all 1s ease-in;
}
<div class="main_div">
  <div class="overlay_div">
    some text
  </div>
</div>

代码工作正常,只需将显示从 none 更改为 block,因为更改 display 时转换不起作用。

.main_div .overlay_div{
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
width:100%;
height:100%;
display:block;/*Change this*/
......
......
}