CSS transition fade in only for element

2019-05-01 22:52发布

问题:

Is there a way to only fade in an element using the CSS transition property? Never really had the need for this before so haven't looked into it, and now I can't seem to find a method of doing so without resorting to JS. Is it possible to set transition to have an immediate return state?

回答1:

There a couple ways to do this, depending on when you want your fade in to occur:

jsFiddle

/***** Fade in on a page load *****/
.fadeInLoad {
    border: 1px solid #48484A;
    font-size: 40px;
    animation: fadeInLoad 5s;
}
@keyframes fadeInLoad {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}

/***** Fade in child when parent hovered *****/
.fadeIn {
    border: 1px solid #48484A;
    font-size: 18px;
    opacity:0;  
    -webkit-transition : all 2s ease-out;
    -moz-transition : all 2s ease-out;
    -o-transition : all 2s ease-out;
    transition : all 2s ease-out;
}
.thisText:hover .fadeIn {
    opacity: 1; 
}

Note: to fade in on page load you need a simple keyframe animation, not a transition.



回答2:

This will fade-in / fade-out on mouse-in / mouse-out. You can set the original opacity to 0 and apply this to your situation.

.item {   
height:200px;
width:200px;
background:red;
-webkit-transition: opacity 1s ease-in-out;
   -moz-transition: opacity 1s ease-in-out;
    -ms-transition: opacity 1s ease-in-out;
     -o-transition: opacity 1s ease-in-out;
        transition: opacity 1s ease-in-out;
}

.item:hover {
zoom: 1;
filter: alpha(opacity=50);
opacity: 0.5;
} 

fiddle

http://jsfiddle.net/7uR8z/6/