如何设置鼠标离开元素的转换(悬停)?

时间:2017-02-17 16:43:04

标签: html css css3 css-transitions

我有多个产品形式,可以在悬停到另一个图像时更改图像。悬停时,转换是平滑的,ease-in-out需要0.3秒。但是,当鼠标离开元素时,转换是突然的,它会立即改变。如何在鼠标离开时进行过渡?

CSS:

.my-reveal .hidden { 
  	display: block !important; 
  	visibility: visible !important;
}
.product:hover .reveal img { 
  	opacity: 1; 
}
.my-reveal { 
  	position: relative; 
}
.my-reveal .hidden { 
  position: absolute; 
  z-index: -1;
  top: 0; 
  width: 100%; 
  height: 100%;  
  opacity: 0;
  -webkit-transition: opacity 0.3s ease-in-out;
  -moz-transition: opacity 0.3s ease-in-out;
  -o-transition: opacity 0.3s ease-in-out;
  transition: opacity 0.3s ease-in-out;  
}
.my-reveal:hover .hidden { 
  z-index: 2;
  opacity: 1;    
}
<div class="my-reveal">
      <img src="" alt="skirt">
      <img src="" alt="skirt">
</div>

3 个答案:

答案 0 :(得分:1)

使用当前布局,您需要做的就是过渡隐藏元素的不透明度,然后进入和退出。

&#13;
&#13;
.my-reveal {
  position: relative;
}
.hidden {
  opacity: 0;
  position: absolute;
  top: 0; left: 0;
  transition: opacity 0.3s ease-in-out;
}
.my-reveal:hover .hidden { 
  opacity: 1;
}
&#13;
<div class="my-reveal">
  <img src="" alt="Bootiful Skirt">
  <img class="hidden" src="" alt="Bootiful Skirt">
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你应该在你的可见图像中添加一个“显示”的类,然后添加这段CSS:

.my-reveal .shown { 
  z-index: 2;
  opacity: 1;    
  -webkit-transition: opacity 0.3s ease-in-out;
  -moz-transition: opacity 0.3s ease-in-out;
  -o-transition: opacity 0.3s ease-in-out;
  transition: opacity 0.3s ease-in-out;  
}
.my-reveal:hover .shown { 
  z-index: -1;
  opacity: 0.3;    
}

这将允许您的可见图像具有不透明状态,不透明度为1,悬浮状态具有易于进出的平滑动画。

答案 2 :(得分:0)

transition添加到z-index媒体资源。在默认状态下,将其延迟设置为等于opacity转换的持续时间,并在:hover状态下将该延迟重置为0

div{
    position:relative; 
}
div>img:first-child{ 
    position:relative;
    z-index:2;
}
div>img:last-child{ 
    left:0;
    opacity:0;
    position:absolute;
    top:0; 
    transition:opacity .3s ease-in-out,z-index 0s linear .3s;  
    z-index:1;
}
div:hover>img:last-child{ 
    opacity:1;    
    transition-delay:0s;
    z-index:3;
}
<div>
    <img src="" alt="skirt">
    <img src="" alt="skirt">
</div>