*IN* 和 *OUT* 的不同 CSS 转换(或从转换状态返回)

问题描述 投票:0回答:2

我有一个在 Ajax 加载事件期间出现的加载图像。通过向 body 元素添加或删除“加载”类来显示/隐藏图像。目前,加载图像的背景大小从 0 到 100% 进行动画处理,并且不透明度逐渐淡化(“返回”过渡反之亦然)。

我希望背景大小过渡在淡出时立即发生(而不是过渡),所以:

  • 淡入:不透明度在 0.2 秒内从 0 到 1,背景大小在 0.2 秒内从 0 到 100%

  • 淡出:不透明度在 0.2 秒内从 1 到 0,背景大小从 100% 到 0 应该立即发生

     #loader {
         width: 100%;
         height: 100%;
         position: fixed;
         top: 0;
         left: 0;
         z-index: -1;
         opacity: 0;
         -moz-opacity: 0;
         transition: all .2s ease-in-out
     }
    
    
     #loader .image {
         width: 400px;
         height: 138px;
         display: block;
         position: absolute;
         z-index: 2000; 
         top: 50%; 
         left: 50%; 
         margin: 0;
         background: url(assets/images/loading.png) no-repeat;
         background-size: 0 0;
         transition: all .2s ease-in-out;
         -webkit-animation: pulse 400ms ease-out infinite alternate;
         -moz-animation: pulse 400ms ease-out infinite alternate;
         -o-animation: pulse 400ms ease-out infinite alternate;
         animation: pulse 400ms ease-out infinite alternate
     }
    
     .loading #loader {z-index: 1000; background-color: rgba(255,255,255,.7)}
    
     .loading #loader .image {
         background-size: 100% 100%; 
         margin: -69px 0 0 -200px;
         transition: opacity .2s ease-in-out
     }
    

我已将此选择器的过渡属性

.loading #loader .image
更改为“不透明度”而不是“全部”,但它仍然执行背景大小过渡。

有谁知道如何用 CSS 实现上述不同的淡入和淡出过渡?

css fadein css-transitions css-animations
2个回答
38
投票

这是一个简化的测试用例:

div {
    background: blue;
    opacity: 0;
    transition: opacity 2s ease-in-out;
}

div.loading {
    opacity: 1;
    background: red;
    transition: opacity 2s ease-in-out, background 1s ease-in;
}

注意

opacity
的淡入和淡出效果相同,但
background
仅淡入,并在淡出时立即变成蓝色。

我使用

:hover
作为示例,但在使用 JavaScript 添加和删除类时,它的工作原理应该是相同的。

演示

如果您想要更具体的示例,请在 dabbletJsfiddle 上提供简化测试用例


0
投票

使用

:hover
实现“转出”效果,使用基本选择器实现“转入”效果:

div {
  background: transparent;
  transition: 3s; /* Mouse Leave */
}

div:hover {
  background: red;
  transition: 1s; /* Mouse Enter */
}

工作示例:https://jsfiddle.net/obtd6nxz/15/

简要说明:

:hover
规则将覆盖基本规则,但仅限于悬停时。一旦鼠标离开,过渡效果将从基本规则集声明的内容开始继续。

© www.soinside.com 2019 - 2024. All rights reserved.