CSS如何使元素淡入淡出然后淡出?

问题描述 投票:32回答:4

通过使用以下css将其类更改为.elementToFadeInAndOut,我可以创建一个不透明度为零的元素:

.elementToFadeInAndOut {
    opacity: 1;
    transition: opacity 2s linear;
}

有没有办法通过编辑同一个类的css,使元素淡入后淡出?

非常感谢您的宝贵时间。

css3 css-transitions fadein fadeout
4个回答
82
投票

使用css @keyframes

.elementToFadeInAndOut {
    opacity: 1;
    animation: fade 2s linear;
}


@keyframes fade {
  0%,100% { opacity: 0 }
  50% { opacity: 1 }
}

这是一个DEMO

.elementToFadeInAndOut {
    width:200px;
    height: 200px;
    background: red;
    -webkit-animation: fadeinout 4s linear forwards;
    animation: fadeinout 4s linear forwards;
}

@-webkit-keyframes fadeinout {
  0%,100% { opacity: 0; }
  50% { opacity: 1; }
}

@keyframes fadeinout {
  0%,100% { opacity: 0; }
  50% { opacity: 1; }
}
<div class=elementToFadeInAndOut></div>

阅读:Using CSS animations

您可以通过执行以下操作来清理代码:

.elementToFadeInAndOut {
    width:200px;
    height: 200px;
    background: red;
    -webkit-animation: fadeinout 4s linear forwards;
    animation: fadeinout 4s linear forwards;
    opacity: 0;
}

@-webkit-keyframes fadeinout {
  50% { opacity: 1; }
}

@keyframes fadeinout {
  50% { opacity: 1; }
}
<div class=elementToFadeInAndOut></div>

11
投票

如果你需要一个没有明确用户操作的fadeIn / Out(比如mouseover / mouseout),你可以使用CSS3 animationhttp://codepen.io/anon/pen/bdEpwW

.elementToFadeInAndOut {
    -webkit-animation: fadeinout 4s linear 1 forwards;
    animation: fadeinout 4s linear 1 forwards;
}

@-webkit-keyframes fadeinout {
  0% { opacity: 0; }
  50% { opacity: 1; }
  100% { opacity: 0; }
}

@keyframes fadeinout {
  0% { opacity: 0; }
  50% { opacity: 1; }
  100% { opacity: 0; }
}

通过设置animation-fill-mode: forwards,动画将保留其最后一个关键帧

通过设置animation-iteration-count: 1,动画将只运行一次(如果需要多次重复此效果,请更改此值)


3
投票

我发现这个链接很有用:css-tricks fade-in fade-out css

这是csstricks帖子的摘要:

CSS类:

.m-fadeOut {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s linear 300ms, opacity 300ms;
}
.m-fadeIn {
  visibility: visible;
  opacity: 1;
  transition: visibility 0s linear 0s, opacity 300ms;
}

在React中:

toggle(){
    if(true condition){
        this.setState({toggleClass: "m-fadeIn"});
    }else{
        this.setState({toggleClass: "m-fadeOut"});
    }
}

render(){
    return (<div className={this.state.toggleClass}>Element to be toggled</div>)
}

-2
投票

试试这个:

@keyframes animationName {
  0%   { opacity:0; }
  50%  { opacity:1; }
  100% { opacity:0; }
}
@-o-keyframes animationName{
  0%   { opacity:0; }
  50%  { opacity:1; }
  100% { opacity:0; }
}
@-moz-keyframes animationName{
  0%   { opacity:0; }
  50%  { opacity:1; }
  100% { opacity:0; }
}
@-webkit-keyframes animationName{
  0%   { opacity:0; }
  50%  { opacity:1; }
  100% { opacity:0; }
}   
.elementToFadeInAndOut {
   -webkit-animation: animationName 5s infinite;
   -moz-animation: animationName 5s infinite;
   -o-animation: animationName 5s infinite;
    animation: animationName 5s infinite;
}
© www.soinside.com 2019 - 2024. All rights reserved.