简体   繁体   中英

Fade out / fade in effect with CSS3

I'm trying to create a fade out / fade in effect with CSS3 animations. Here is my CSS :

#buttonright, #buttonleft{
-webkit-transition:opacity 0.5s linear;
-moz-transition:opacity 0.5s linear;
-o-transition:opacity 0.5s linear;
-ms-transition:opacity 0.5s linear; 
transition:opacity 0.5s linear;
}

And the Javascript (i'm using jquery) :

$('#buttonleft').css("opacity","0");
$('#buttonright').css("opacity","0");
$('#buttonleft').css("opacity","1");
$('#buttonright').css("opacity","1");

It looks like the browser think it's stupid to set the opacity to 0 then to set it back to 1. Does someone has a possible solution ?

Thank you.

Edit: Regard yaki's answer for a pure CSS3 solution.

You're not giving the browser enough time to complete the transition. If you add a setTimeout to the latter statements, it should work.

Something like this:

$('#buttonleft').css("opacity","0");
$('#buttonright').css("opacity","0");
setTimeout(function(){$('#buttonleft').css("opacity","1");}, 5000);
setTimeout(function(){$('#buttonright').css("opacity","1");}, 5000);

Actually accepted solution is not CSS3 solution (it's still requires some javascript code). Please check the code below.

html:

<a id='buttonleft'>Button left</a>
<a id='buttonright'>Button right</a>

css:

 #buttonleft, #buttonright {
    text-align: left;
    background: rgb(180,180,255);
    opacity:0.5;

    /* property duration timing-function delay */
    -webkit-transition: opacity 500ms linear 100ms;
    -moz-transition: opacity 500ms linear 100ms;
    -o-transition: opacity 500ms linear 100ms;
    transition: opacity 500ms linear 100ms;
    }

#buttonleft:hover, #buttonright:hover {
    opacity: 1.0;
}

You can use CSS3 animations now that it is more supported than when you asked the original question. I've created a jsFiddle showing how to do this on hover .

@keyframes demo {
    from {
      animation-timing-function: ease;
      opacity: 1;
    }
    50% {
      animation-timing-function: ease-in;
      opacity: 0;
    }
    to {
      animation-timing-function: ease-inout;
      opacity: 1;
    }
}

img:hover
{
    animation-delay: 0s;
    animation-duration: 2s;
    animation-iteration-count: 1;
    animation-name: demo;
}

something like this?

$('#button').hover(
    function() { 
        $(this).animate({opacity: 0}, 500); 
    },
    function() { 
        $(this).animate({opacity: 1}, 500);
    }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM